Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a function every n hours in server side swift?

Tags:

swift

vapor

I'm looking for a Swift counterpart to Django's Celery which allows a function to execute every given amount of time.

I need a solution that works on server side Swift, meaning not all of Foundation is available, and something that's not for iOS / Mac.

I am using the Vapor framework.

like image 231
Berry Avatar asked Aug 10 '17 23:08

Berry


1 Answers

You have three main options.

For a timer managed within your server app (i.e. restarting the server resets your timers) you can use Dispatch:

import Dispatch
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
  // task
}
timer.scheduleRepeating(deadline: .now() + .seconds(3600), interval: .seconds(3600), leeway: .seconds(60))
timer.activate()

Similarly, you can use the third party Jobs package created by a Vapor contributor:

import Jobs
Jobs.add(interval: .hours(1)) {
  // task
}

If you want the function to be run at particular times of day independent of your server's uptime, there's no beating cron (or its relatives). Your cron job should either call a Vapor Command on the binary, or hit a protected URL-route with curl.

like image 109
tobygriffin Avatar answered Oct 13 '22 23:10

tobygriffin