Run code at a certain time according to the system clock

我的未来我决定 提交于 2019-12-24 08:57:40

问题


What's the best way of running code when the system clock changes to a certain time? Obviously I could poll, but that seems inefficient.

I don't want a timer; I want to be able to do something at (for instance) 10pm every evening.


回答1:


NSTimer is pretty much how you do something later in Cocoa, and it's possible to create one with a "fire date", but that date will be put off if the computer goes to sleep in the meantime (or if the clock changes).

Polling via a timer might not be such a bad option; it allows you to have many events scheduled but only a single mechanism activating them. A timer that repeats every 15 or 30 seconds and looks through a list of NSDates to see if something should happen shouldn't have a meaningful performance impact.

Another option is using NoodleKit's NSTimer category that accounts for clock changes. There's a blog post about it: http://www.noodlesoft.com/blog/2010/07/01/playing-with-nstimer/, and the code is available on GitHub: https://github.com/MrNoodle/NoodleKit The timer registers itself for NSWorkspace sleep/wake notifications as well as time zone change notifications and adjusts its fire time accordingly.




回答2:


I'm not sure this is what you are looking for but you might want to try automator, as explained here.



来源:https://stackoverflow.com/questions/11404348/run-code-at-a-certain-time-according-to-the-system-clock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!