tags:

views:

68

answers:

2
+4  Q: 

Python Time Delays

I want to know how to call a function after a certain time. I have tried time.sleep() but this halts the whole script. I want the script to carry on, but after ???secs call a function and run the other script at the same time

+8  A: 

Have a look at threading.Timer. It runs your function in a new thread.

from threading import Timer

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
Mark Byers
multithreading... hmm, sounds familiar. Isn't that were there is more than one process?Well anyway that looks right.if I use t.start() more than once, does it carry on, give me an error or restart the timer?
drnessie
@drnessie: "Isn't that were there is more than one process?" No - it's when you have more than one thread. "if I use t.start() more than once, does it carry on, give me an error or restart the timer?" - You get an error 'RuntimeError: thread already started' which you can easily verify for yourself by duplicating the last line in the above source code and running it.
Mark Byers
Is there any way of getting rid of the error, apart from stopping then re-starting the timer?
drnessie
@drnessie: You could for example create a new timer. You probably don't want too many at once though, because each timer has its own thread.
Mark Byers
@Mark one last thing... does the thread destroy itself when the target function is finished?
drnessie
+2  A: 

If you want a function to be called after a while and not to stop your script you are inherently dealing with threaded code. If you want to set a function to be called and not to worry about it, you have to either explicitly use multi-threading - like em Mark Byers's answr, or use a coding framework that has a main loop which takes care of function dispatching for you - like twisted, qt, gtk, pyglet, and so many others. Any of these would require you to rewrite your code so that it works from that framework's main loop.

It is either that, or writing some main loop from event checking yourself on your code - All in all, if the only thing you want is single function calls, threading.Timer is the way to do it. If you want to use these timed calls to actually loop the program as is usually done with javascript's setTimeout, you are better of selecting one of the coding frameworks I listed above and refactoring your code to take advantage of it.

jsbueno
This code is not workingthreading.Timer( 30.0, self.timestart(window) ).start()It is calling self.timestart, giving the arg window, but it is doing it Immediately, not after 30secs Would've asked Mark, but I've bothered him enough, and you know what your talking 'bout too :)
drnessie