Search code examples
swiftdispatch-async

Schedule function execution in swift


I'm developing a simple app in Swift and I need to schedule a function execution every 24 hours. I'm aware of the method:

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

that could solve my problem but, is this the right solution for a 24 hours delay? Thanks


Solution

  • Theoretically, this is possible. The problem is that your app would have to run in the foreground for 24 hours, which is very unlikely to happen. Unfortunately, you can not run background tasks just like that.

    The solution:

    Just make it look like the function would execute in the background. Every time the update function is called, simply save the Int(Date().timeIntervalSince1970) to UserDefaults. This works like a timestamp and saves the last time you called your update function. Every time in the viewDidLoad()-function (not sure if it's called the same on Mac apps, but you can imagine what I mean) call:

    If let timestamp = UserDefaults.standard.integer(forKey: "yourTimestampKey") {
    
       let currentTimestamp = Date().timeIntervalSince1970
       if (currentTimestamp - timestamp) > 86400 { // number of seconds in 24 hours 
          // the last time your function was updated was at least 24h ago
    
          update()
       }
    
    }
    

    That's how you can make it appear like it was updated in the background. I use this all the time in my apps and it works perfectly.

    EDIT:

    Maybe, just in case the app does indeed run 24 hours in a row, I would set up the upper function that you posted first as well.