3

Is there a possibility of scheduling tasks on a server-side Swift framework, preferably Kitura?

I need to schedule tasks; for example, wiping a database everyday at 3AM.

basedgod
  • 2,517
  • 1
  • 17
  • 18

3 Answers3

9

In Kitura at least, we don't provide an special functionality for that.

One thing you can consider using is Dispatch, which will work very well for your example of deleting the database everyday at 3AM. You can create a DispatchSourceTimer that dispatches some code after some interval once or repeatedly.

DispatchSourceTimer.scheduleOneshot(deadline: DispatchTimer, leeway: DispatchTimeInterval)
DispatchSourceTimer.scheduleRepeating(deadline: DispatchTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval)
  • Thank you! This works great on macOS. But I am getting errors like `error: use of undeclared type 'DispatchSourceTimer'` when deploying to Heroku. Is there some trick to do, to make Dispatch working on Heroku / Unix? – basedgod Nov 22 '16 at 20:55
  • Great! Glad it's working for you. Dispatch is a very handy library. – Robert F. Dickerson Nov 22 '16 at 22:42
  • Nice! I was looking for a "entire" solution with Swift, without batch, crontab, etc. Did you realize performance issues with this solution? – Thomás Pereira Jan 31 '17 at 11:37
0

I solved this problem by adding an endpoint that triggers the action. Then I have a cron task that triggers a curl command to hit that endpoint at the appropriate time.

I secure this by proxying all communication with the outside world through nginx, and just blocking this endpoint in my nginx configuration. The Swift based server app serves only to the local host, which works with the curl command, and to feed to nginx, but is blocked for anything outside the server.

Mr. Berna
  • 10,525
  • 1
  • 39
  • 42
0

It took me sometime to get this working, so here's what I've got:

    let timer = DispatchSource.makeTimerSource()
    timer.setEventHandler() {
        // Coded I want to execute after a delay
    }

    let now = DispatchTime.now()
    let delayInSeconds:UInt64 = 5
    let deadline = DispatchTime(uptimeNanoseconds: now.uptimeNanoseconds + delayInSeconds*UInt64(1e9))

    timer.scheduleOneshot(deadline: deadline)
    timer.activate()

This is a little cumbersome. Ideas are welcome.

Chris Prince
  • 7,288
  • 2
  • 48
  • 66