Run a function every X minutes - Python

て烟熏妆下的殇ゞ 提交于 2019-11-29 12:23:31

问题


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.

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)

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.

Any suggestions on how to solve this problem? Multithreading? Interrupts? Please keep in mind that I'm using python.

Thanks.


回答1:


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



回答2:


This is exactly like my answer here

If the time is not critical to be exact to the tenth of a second, use

glib.timeout_add_seconds(60, ..)

else as above.

timeout_add_seconds allows the system to align timeouts to other events, in the long run reducing CPU wakeups (especially if the timeout is reocurring) and save energy for the planet(!)




回答3:


gtk.timeout_add appears to be deprecated, so you should use

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

gobject.timeout_add( 60*1000, my_timer )



回答4:


try:

import wx
wx.CallLater(1000, my_timer)


来源:https://stackoverflow.com/questions/1052574/run-a-function-every-x-minutes-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!