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

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

}