Reputation: 2035
I'm trying to get my app to call a function at specific time intervals. For example, I might want the function to be called every hour on the hour, so at 1:00 AM, 2:00 AM, and so on. I have tried doing this with an NSTimer, but I find that it has trouble staying in sync when resuming after the machine sleeps or is powered off. Is there a way for my app to detect when we have reached a specific date and time and to call a function at that time? Thanks.
Upvotes: 2
Views: 1333
Reputation: 491
You could use a helper method similar to below in combination with the NSTimer. The timer could fire its selector function every sec/minute/etc in which you pass this helper a pair of currentDate/endDate and when the returned value is <= 0 then execute your timed event function once with a flag and move your endDate forward an hour.
func timeBetween(currentDate: NSDate, endDate: NSDate) -> Double
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Second], fromDate: currentDate, toDate: endDate, options: [])
return Double(components.second)
}
Upvotes: 1
Reputation: 2002
You could try Grand Central Dispatch. Specifically use dispatch_walltime() to create a dispatch_time_t
representing the time you want the job to run and then use dispatch_after() to submit the job to Grand Central Dispatch for execution at the specified time.
Upvotes: 3
Reputation: 185862
Run it every minute and test whether ≥ 1h has elapsed since the last invocation.
Upvotes: 1