12

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

谢谢。

4

4 回答 4

23

不要在睡眠中使用这样的循环,它会阻止 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
于 2009-06-27T10:34:54.527 回答
9

这和我的回答一模一样

如果时间不是精确到十分之一秒,请使用

glib.timeout_add_seconds(60, ..)

其他同上。

timeout_add_seconds允许系统将超时与其他事件对齐,从长远来看减少 CPU 唤醒(特别是如果超时再次发生)并为地球节省能源(!)

于 2009-08-21T00:01:57.993 回答
5

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

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

gobject.timeout_add( 60*1000, my_timer )
于 2011-01-10T20:11:00.343 回答
0

尝试:

import wx
wx.CallLater(1000, my_timer)
于 2013-01-22T22:02:39.537 回答