Time delay function?

Alan Kennedy alanmk at hotmail.com
Sun Oct 20 07:29:56 EDT 2002


Ken wrote:

> Hi, is there a command in Python similar to javascript's
> window.settimeout(), where you can set a few seconds delay before
> executing a function?

Ken,

Javascript allows you to execute stuff "in the foreground" while your
timer counts away "in the background". I presume you want to be
executing other stuff in the interim, i.e. do you want the timeout stuff
to happen in the "background"?

If yes, there are a couple of different ways you could approach this.

1. If you're working on unix, then you can use the "alarm" method in the
"signal" module. This will set an alarm to go off after a particular
time. You also use the signal method in the same module to ensure that a
particular function is executed when the alarm signal is raised. But
this doesn't work on Windows. See an example at

http://www.python.org/doc/2.0/lib/Signal_Example.html

2. If you want a cross platform solution, then you should use
multithreading. You create a second thread of execution, make it wait
for the desired period of time, then execute your function. 

Fortunately, this is such a common case that there is a convenience
class provided in the standard library (from python 2.2 onwards) that
achieves exactly this, without requiring too much getting your hands
dirty in threading (if you're not comfortable with that kind of thing).

The class is called "Timer", and is documented, with an example, here

http://www.python.org/doc/2.2/lib/timer-objects.html

If you cannot use python 2.2, here is some sample code that achieves the
same thing in older versions of python

import threading
import time

class myTimer(threading.Thread):

    def __init__(self, timeout, func):
        threading.Thread.__init__(self)
        self.timeout = timeout
        self.func = func

    def run(self):
        time.sleep(self.timeout)
        self.func()

# Now test it

def sayHello():
    print "Rip van Winkle awakes!"

timer = myTimer(10, sayHello)
timer.start()
# Count to 11 seconds
for sec in range(15):
    print "waiting...... %d" % sec
    time.sleep(1)



regards,

alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan



More information about the Python-list mailing list