简单的闹钟,每秒查看时间
我正在用 python 创建一个闹钟,有一个简单的问题:
我的闹钟的分辨率需要精确到秒。目前我有一个线程每 0.5 秒唤醒一次,并检查是否到了开始发出噪音的时间。
我唯一担心的是,不知何故,系统在某个时刻完全过载,并且闹钟不会响起,因为闹钟线程在应该检查时间的那一刻仍在休眠。
所以我的问题是,每 0.05 秒检查一次会更好吗?或者有没有办法在特定时间向 python 注册事件处理程序,这样我就不必自己不断检查时间。
I'm creating an alarm clock in python and have a simple question:
My alarm clock's resolution needs to be down to the second. Currently I have a thread that wakes every 0.5 seconds, and checks whether its time to start making noise.
My only concern is that somehow the system gets completely overloaded at some point and the alarm does not sound because the alarm clock thread was still sleeping during the second it was supposed to check the time.
So my question is, would checking every 0.05 seconds be better? Or is there a way to register an event handler with python for a specific time, so I dont have to keep checking the time myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查标准
signal
模块 的计时器函数。另外,如果您已经知道何时触发操作,为什么不在执行之前执行 time.sleep(seconds) 呢? (显然,
秒
应该是触发操作的剩余时间,以秒为单位)Check the standard
signal
module for timer functions.Also, if you already know when to trigger your action, why not execute
time.sleep(seconds)
just before executing it? (seconds
should be the time left to trigger the action in seconds, obviously)这不是最好的解决方案。不能保证您被锁定超过一秒钟。
您应该坚持 0.5 秒的分辨率(如果没有生命依赖它,则更糟)并在或超过到期时间时触发事件,并在每个事件已触发时保留一个标志。然后它总是会恰好一次被触发,并且尽可能接近目标时间。
That's not the best solution. It's no guarantee you are locked out for more than one second.
You should stick to 0.5 second resolution (or worse if no lives depend on it) and fire the event whenever it is at or past the due time, and keep a flag per event if it has been fired. Then it will always be fired at exactly once, and as close to the target time as achievable.