Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 999
Joe Huang Avatar asked Jan 27 '17 16:01

Joe Huang


2 Answers

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.

like image 56
tobygriffin Avatar answered Nov 18 '22 16:11

tobygriffin


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

}
like image 42
Kerusan Avatar answered Nov 18 '22 17:11

Kerusan