我可以使用计时器,例如Vapor中的NSTimer
(服务器端Swift)吗?
我希望用Vapor编写的服务器可以偶尔主动执行一些任务。例如,每15分钟从网上轮询一些数据。
如何用Vapor实现这一目标?
如果您只需要一个简单的计时器被触发,可以使用Dispatch
schedule()
函数一次或多次创建它。如果需要,您可以暂停,恢复和取消它。
这是一个代码片段:
import Vapor
import Dispatch
/// Controls basic CRUD operations on `Session`s.
final class SessionController {
let timer: DispatchSourceTimer
/// Initialize the controller
init() {
self.timer = DispatchSource.makeTimerSource()
self.startTimer()
print("Timer created")
}
// *** Functions for timer
/// Configure & activate timer
func startTimer() {
timer.setEventHandler() {
self.doTimerJob()
}
timer.schedule(deadline: .now() + .seconds(5), repeating: .seconds(10), leeway: .seconds(10))
if #available(OSX 10.14.3, *) {
timer.activate()
}
}
// *** Functions for cancel old sessions
///Cancel sessions that has timed out
func doTimerJob() {
print("Cancel sessions")
}
}