How to use timer in Vapor (server-side Swift)?

梦想与她 提交于 2019-12-19 07:18:08

问题


Can I use timer, such as NSTimer in Vapor (server-side Swift)?

I hope my server written in Vapor can do some tasks proactively once in a while. For example, polling some data from the web every 15 mins.

How to achieve this with Vapor?


回答1:


If you can accept your task timer being re-set whenever the server instance is recreated, and you only have one server instance, then you should consider the excellent Jobs library.

If you need your task to run exactly at the same time regardless of the server process, then use cron or similar to schedule a Command.




回答2:


If you just need a simple timer to be fired, once or repeatedly you can create it using the Dispatch schedule() function. You can suspend, resume and cancel it if needed.

Here is a code snippet to do it:

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")
}

}


来源:https://stackoverflow.com/questions/41898944/how-to-use-timer-in-vapor-server-side-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!