每 X 分钟运行一个函数 - Python
我正在使用 Python 和 PyGTK。 我感兴趣的是运行某个函数,该函数每隔几分钟从串行端口获取数据并保存它。
目前,我正在使用时间库中的 sleep() 函数。 为了能够进行处理,我的系统设置如下:
import time
waittime = 300 # 5 minutes
while(1):
time1 = time.time()
readserial() # Read data from serial port
processing() # Do stuff with serial data, including dumping it to a file
time2 = time.time()
processingtime = time2 - time1
sleeptime = waittime - processingtime
time.sleep(sleeptime)
此设置允许我从串行端口读取数据之间有 5 分钟的间隔。 我的问题是,我希望能够让 readserial() 函数每 5 分钟暂停一次正在发生的事情,并且能够一直执行操作,而不是使用 time.sleep() 函数。
关于如何解决这个问题有什么建议吗? 多线程? 中断? 请记住我正在使用 python。
谢谢。
I'm using Python and PyGTK. I'm interested in running a certain function, which gets data from a serial port and saves it, every several minutes.
Currently, I'm using the sleep() function in the time library. In order to be able to do processing, I have my system set up like this:
import time
waittime = 300 # 5 minutes
while(1):
time1 = time.time()
readserial() # Read data from serial port
processing() # Do stuff with serial data, including dumping it to a file
time2 = time.time()
processingtime = time2 - time1
sleeptime = waittime - processingtime
time.sleep(sleeptime)
This setup allows me to have 5 minute intervals between reading data from the serial port. My issue is that I'd like to be able to have my readserial() function pause whatever is going on every 5 minutes and be able to do things all the time instead of using the time.sleep() function.
Any suggestions on how to solve this problem? Multithreading? Interrupts? Please keep in mind that I'm using python.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要在 sleep 中使用这样的循环,它会阻止 gtk 处理任何 UI 事件,而是使用 gtk 计时器,例如
Do not use such loop with sleep, it will block gtk from processing any UI events, instead use gtk timer e.g.
这与我在这里的回答
如果时间不要求精确到十分之一秒,请使用
上面的 else。
timeout_add_seconds 允许系统将超时与其他事件对齐,从长远来看减少 CPU 唤醒(特别是超时重复发生时)和 为地球节省能源(!)
This is exactly like my answer here
If the time is not critical to be exact to the tenth of a second, use
else as above.
timeout_add_seconds allows the system to align timeouts to other events, in the long run reducing CPU wakeups (especially if the timeout is reocurring) and save energy for the planet(!)
gtk.timeout_add 似乎已被弃用,因此您应该使用
gtk.timeout_add appears to be deprecated, so you should use
尝试:
try: