Run code at a certain time according to the system

2019-08-14 23:10发布

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.

2条回答
smile是对你的礼貌
2楼-- · 2019-08-14 23:42

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

查看更多
迷人小祖宗
3楼-- · 2019-08-14 23:52

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.

查看更多
登录 后发表回答