Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function every X minutes - Python

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.

like image 299
mouche Avatar asked Jun 27 '09 10:06

mouche


1 Answers

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 )
like image 136
wwwilliam Avatar answered Sep 19 '22 18:09

wwwilliam