7

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.

Berry
  • 2,143
  • 4
  • 23
  • 46
  • I have answered this question [here](https://stackoverflow.com/questions/41898944/how-to-use-timer-in-vapor-server-side-swift/55539678#55539678) with a code snippet – Kerusan Apr 05 '19 at 16:26

1 Answers1

11

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.

tobygriffin
  • 5,339
  • 4
  • 36
  • 61