每 X 分钟运行一个函数 - Python [英] Run a function every X minutes - Python
问题描述
我正在使用 Python 和 PyGTK.我对运行某个函数感兴趣,该函数每隔几分钟从串行端口获取数据并保存一次.
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.
目前,我正在使用时间库中的 sleep() 函数.为了能够进行处理,我的系统设置如下:
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)
此设置允许我在从串行端口读取数据之间有 5 分钟的时间间隔.我的问题是我希望能够让我的 readserial() 函数每 5 分钟暂停一次正在发生的事情,并且能够一直做事情而不是使用 time.sleep() 函数.
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.
有关如何解决此问题的任何建议?多线程?中断?请记住,我使用的是 python.
Any suggestions on how to solve this problem? Multithreading? Interrupts? Please keep in mind that I'm using python.
谢谢.
推荐答案
不要在 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.
def my_timer(*args):
return True# do ur work here, but not for long
gtk.timeout_add(60*1000, my_timer) # call every min
这篇关于每 X 分钟运行一个函数 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!