Timers in Python?

Gilles Lenfant glenfant at equod.com.nospam
Mon Dec 18 18:46:13 CET 2000


Have a look to "threading" package and time.sleep(...) function.
Seems that's all you need!
Important, use threading.Lock() objects if threads may use not sharable
resources.
Warning, binary distributions of Python/Unix are not always compiles with
threads options.
You may need to compile Python from sources if required.

import threading, time

Mylock = threading.Lock()

class TimeScheduled(threading.Thread):
    def __init__(self, function, delay):
        self.function = function
        self.delay = delay

    def run(self):
        self.alive = 1
        while self.alive:
            Mylock.acquire() # optional (depends whether unsharable
resources used or not)
            self.function()
            Mylock.release() # optional
            time.sleep(self.delay)

    def kill(self):
        self.alive = 0

def sayhello():
    # Very complex stuff
    print "Hello world"
...
# Every 2 minutes
scheduledHello = TimeSceduled(sayhello, 120)
scheduledHello.start()
...
scheduledHello.kill()
...

"Daniel" <Daniel.Kinnaer at AdValvas.be> a écrit dans le message news:
3a3e42ef.16144323 at news.skynet.be...
>
> Is there an equivalent of the Delphi Timer-component in Python as
> well?  That is, I want to have two Timers : Timer1 needs to activate
> itself every 2 minutes and Timer2 needs to activate itself every 7
> minutes.
>
> In Delphi I can have 2 Timer.events  :
>
> procedure TForm1.Timer1Timer(Sender: TObject);
> begin
>   //do a special task1
> end;
>
> procedure TForm1.Timer2Timer(Sender: TObject);
> begin
>   //do a special task2
> end;
>
> How is this done in Python?
>
> Thanks for helping out.  Daniel




More information about the Python-list mailing list