2009-06-27 57 views
11

我正在使用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。

謝謝。

回答

23

不要在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

10

這是完全一樣my answer here

如果時間不準確到十分之一秒的關鍵,使用

glib.timeout_add_seconds(60, ..) 

其他同上。

timeout_add_seconds允許系統對準超時其他事件,從長遠來看,減少CPU喚醒(尤其是如果超時reocurring)和save energy for the planet(!)

4

gtk.timeout_add似乎被棄用,因此,你應該使用

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

gobject.timeout_add(60*1000, my_timer) 
1

嘗試:

import wx 
wx.CallLater(1000, my_timer)