swift - 每天午夜运行代码

标签 swift macos timer

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

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

}

最佳答案

不需要计时器。观察通知

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()
{
    print("day did change")
}

或者使用基于闭包的 API

NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object: nil, queue: .main) { _ in
   print("day did change")
}

或合并

var subscription : AnyCancellable?

subscription = NotificationCenter.default.publisher(for: .NSCalendarDayChanged)
    .sink { _ in print("day did change") }

或者使用 async/await (Swift 5.5+)

Task {
    for await _ in NotificationCenter.default.notifications(named: .NSCalendarDayChanged) {
        print("day did change")
    }
}

关于swift - 每天午夜运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44973888/

相关文章:

swift - 转义采用可选参数的完成处理程序有时会使 Swift 崩溃

xcode - 如何同时发送一定数量的 POST/GET 请求?

swift - SwiftUI Xcode 12 for macOS App 工具栏中的搜索栏

c++ - 周期性时间间隔调用函数的API

javascript - 如何拥有一个无法在 javascript 中修改的计时器?

swift - 在scenekit中设置游戏场景时出错

ios - 按字典中的时间戳对 TableView 进行排序

ios - 类型为 Void 的 appendAttributedString 返回值

macos - 在 zsh 中哪里放置 $PATH 变量断言?

c# - 如何立即触发 timer.Elapsed 事件