Run code at a certain time according to the system

2019-08-14 23:32发布

问题:

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.