根据系统时钟在特定时间运行代码 [英] Run code at a certain time according to the system clock

查看:72
本文介绍了根据系统时钟在特定时间运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当系统时钟更改为特定时间时,运行代码的最佳方法是什么?显然我可以投票,但这似乎效率很低.

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.

我不想要计时器;我希望能够(例如)每天晚上10点做某事.

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

推荐答案

NSTimer差不多是您以后在可可粉中所做的工作,并且可以创建一个带有起火日期"的日期,但是该日期将被放入如果计算机在此期间进入睡眠状态(或者时钟发生变化),则关闭.

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).

通过计时器轮询可能不是一个糟糕的选择.它允许您安排许多事件,但是只有一种机制可以激活它们.计时器每15或30秒重复一次,并查看NSDates列表以查看是否应该进行某些操作,这不会对性能产生有意义的影响.

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.

另一个选择是使用NoodleKit的NSTimer类别来说明时钟变化.有一篇关于它的博客文章: http://www.noodlesoft .com/blog/2010/07/01/playing-with-nstimer/,该代码在GitHub上可用:

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.

这篇关于根据系统时钟在特定时间运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆