每 X 分钟运行一个函数 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1052574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run a function every X minutes - Python
提问by mouche
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.
我正在使用 Python 和 PyGTK。我对运行某个函数感兴趣,它每隔几分钟从串行端口获取数据并保存它。
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:
目前,我正在使用时间库中的 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)
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.
此设置允许我在从串行端口读取数据之间有 5 分钟的时间间隔。我的问题是我希望能够让我的 readserial() 函数每 5 分钟暂停一次正在发生的事情,并且能够一直做事情而不是使用 time.sleep() 函数。
Any suggestions on how to solve this problem? Multithreading? Interrupts? Please keep in mind that I'm using python.
有关如何解决此问题的任何建议?多线程?中断?请记住,我正在使用 python。
Thanks.
谢谢。
回答by Anurag Uniyal
Do not use such loop with sleep, it will block gtk from processing any UI events, instead use gtk timer e.g.
不要在睡眠中使用这样的循环,它会阻止 gtk 处理任何 UI 事件,而是使用 gtk 计时器,例如
def my_timer(*args):
return True# do ur work here, but not for long
gtk.timeout_add(60*1000, my_timer) # call every min
回答by u0b34a0f6ae
This is exactly like my answer here
这和我在这里的回答一模一样
If the time is not critical to be exact to the tenth of a second, use
如果时间不是精确到十分之一秒的关键,请使用
glib.timeout_add_seconds(60, ..)
else as above.
其他如上。
timeout_add_secondsallows 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(!)
timeout_add_seconds允许系统将超时与其他事件对齐,从长远来看减少 CPU 唤醒(特别是如果超时重复发生)并为地球节省能源(!)
回答by wwwilliam
gtk.timeout_add appears to be deprecated, so you should use
gtk.timeout_add 似乎已被弃用,因此您应该使用
def my_timer(*args):
# Do your work here
return True
gobject.timeout_add( 60*1000, my_timer )
回答by Leon
try:
尝试:
import wx
wx.CallLater(1000, my_timer)