每天午夜运行代码

Ken*_*Chu 3 macos timer swift

我想每天午夜更新状态。但计时器是按时间间隔的。如何按天设置间隔

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() {

}
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 6

不需要计时器。遵守通知

static let NSCalendarDayChanged: NSNotification.Name
Run Code Online (Sandbox Code Playgroud)

每当系统日历日更改时发布,由系统日历、区域设置和时区确定。此通知不提供对象。

如果设备在日期变化时处于睡眠状态,则该通知将在唤醒时发布。如果设备已休眠多天,则在唤醒时只会发布一条通知。

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

...

func calendarDayDidChange()
{
    // do something at midnight
}
Run Code Online (Sandbox Code Playgroud)