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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
NSTimeris 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
NSDatesto see if something should happen shouldn’t have a meaningful performance impact.Another option is using NoodleKit’s
NSTimercategory 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 forNSWorkspacesleep/wake notifications as well as time zone change notifications and adjusts its fire time accordingly.