8

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?

Joe Huang
  • 6,296
  • 7
  • 48
  • 81

2 Answers2

8

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.

tobygriffin
  • 5,339
  • 4
  • 36
  • 61
  • `Jobs` is the solution, thanks! Just one stupid question, how do I keep my server instance running without exiting (if I remove `droplet.run()`) – Joe Huang Jan 28 '17 at 01:42
  • I'm not sure I understand; why do you want to remove `droplet.run()`? – tobygriffin Jan 28 '17 at 02:37
  • @tobygirffin since I used node.js before, so I keep considering the server instance can do the same (not just a web framework). – Joe Huang Jan 28 '17 at 05:23
  • I'm afraid I still don't understand. What is achieved by removing the serving part of your Vapor app? – tobygriffin Jan 28 '17 at 06:02
  • sorry, I am new to Vapor & server-side Swift. How about this... is there a library for server-side Swift for this node.js async library: https://github.com/caolan/async ? – Joe Huang Jan 28 '17 at 09:53
7

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

}
roschach
  • 8,390
  • 14
  • 74
  • 124
Kerusan
  • 71
  • 1
  • 3