每X分钟运行一次函数 - 蟒蛇

问题描述:

我正在使用Python和PyGTK。我对运行某个函数感兴趣,它每隔几分钟就会从串口获取数据并保存它。每X分钟运行一次函数 - 蟒蛇

目前,我在时间库中使用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。

谢谢。

不要在sleep中使用这样的循环,它会阻止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 
+0

感谢。这就是我正在寻找的东西。 – mouche 2009-06-27 10:37:17

+4

您的回调需要返回“True”或“False”来继续或终止事件。 – 2009-06-27 11:47:02

+2

问题是旧的,但如果有人需要在Gtk + 3上执行此操作,则函数为`GLib.timeout_add(delay,function,arg)` – arkocal 2014-02-10 12:33:07

这是完全一样my answer here

如果时间不准确到十分之一秒的关键,使用

glib.timeout_add_seconds(60, ..) 

其他同上。

timeout_add_seconds允许系统对准超时其他事件,从长远来看,减少CPU唤醒(尤其是如果超时reocurring)和save energy for the planet(!)

gtk.timeout_add似乎被弃用,因此,你应该使用

def my_timer(*args): 
    # Do your work here 
    return True 

gobject.timeout_add(60*1000, my_timer) 

尝试:

import wx 
wx.CallLater(1000, my_timer)