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?
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.
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With