Joe Huang
Joe Huang

Reputation: 6570

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

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?

Upvotes: 8

Views: 2688

Answers (2)

Kerusan
Kerusan

Reputation: 71

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

}

Upvotes: 7

tobygriffin
tobygriffin

Reputation: 5421

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.

Upvotes: 8

Related Questions