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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With