How to launch a function at regular time intervals ?
Frank Millman
frank at chagford.com
Thu Aug 13 00:20:05 EDT 2009
On Aug 12, 11:09 pm, David <davigier at googlemail.com> wrote:
> Hi all, I'm trying to launch a function at regular time intervals but
> cannot find the way to do it.
I assume you want your main program to continue running, while launching the
function to run in the background.
If you need this as a general capability, Christian's approach is probably
the way to go.
In my case I had one specific requirement, and found it easier to write a
dedicated solution, as follows -
import threading
class MyFunction(threading.Thread):
"""Perform function every 30 seconds in separate thread"""
def __init__(self):
threading.Thread.__init__(self)
self.event = threading.Event()
def run(self):
while not self.event.is_set():
# either call your function here,
# or put the body of the function here
self.event.wait(30) # wait for 30 seconds
def stop(self):
self.event.set()
At the start of the main program, I have the following -
func = MyFunction()
func.start()
When closing the main program, I have -
func.stop()
func.join()
It is trivial to modify this to pass the interval, plus any other parameters
required, as arguments.
HTH
Frank Millman
More information about the Python-list
mailing list