How to run a repeating timer every n minutes?

Frank Millman frank at chagford.com
Thu Oct 29 07:48:43 EDT 2009


Ashish Vyas wrote:

> Dear All
>
> How do I write a code that gets executed 'every x' minutes?
>

[...]

> Regards,
> Ashish Vyas

Here is one way -

import threading

class Timer(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()

    def run(self):
        while not self.event.is_set():
             """ The things I want to do go here. """
             self.event.wait(number_of_seconds_to_wait)

    def stop(self):
        self.event.set()

In your main program -
  - to start the timer
      tmr = Timer()
      tmr.start()

  - to stop the timer
      tmr.stop()

It is easy to extend this by passing the number_of_seconds_to_wait, or a 
function name to be executed, as arguments to the Timer.

Frank Millman






More information about the Python-list mailing list