Run code at midnight everyday

2020-04-21 08:02发布

问题:

I want to update status at midnight everyday. but timer is by interval. how can I set the interval by day

var timer = Timer()

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

// called every time interval from the timer
func timerAction() {

}

回答1:

No timer needed. Observe the notification

static let NSCalendarDayChanged: NSNotification.Name

Posted whenever the calendar day of the system changes, as determined by the system calendar, locale, and time zone. This notification does not provide an object.

If the the device is asleep when the day changes, this notification will be posted on wakeup. Only one notification will be posted on wakeup if the device has been asleep for multiple days.

NotificationCenter.default.addObserver(self, selector:#selector(calendarDayDidChange), name:.NSCalendarDayChanged, object:nil)

...

func calendarDayDidChange()
{
    // do something at midnight
}