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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Method 2
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.
Method 3
If the non-block feature is not needed, just use time.sleep(5) which will work anywhere and save your life.
Method 4
Okey, not a perfect solution but i used the following since my job was simple enough:
counter_time = 0 while True: time.sleep(0.1) counter_time = counter_time + 0.1
Now you have time just use if to do something at spesific time. My code was running inside the while loop so this worked for me. You can do the same or use threading to run this infinite loop together with your own code.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0