每X分钟运行一个函数 - Python [英] Run a function every X minutes - Python

查看:199
本文介绍了每X分钟运行一个函数 - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆