Alright, I want to know how to delay a portion of a program without pausing the entire program.
I'm not necessarily good at python so if you could give me a relatively simple answer if possible, that would be great.
I want to have a turtle draw a circle on screen every time this function is called, this is what I have:
import time
from random import randint
turtle5 = turtle.Turtle()
coinx = randint(-200, 200)
coiny = randint(-200, 200)
turtle5.pu()
turtle5.goto(coinx, coiny)
turtle5.pd()
turtle5.begin_fill()
turtle5.fillcolor("Gold")
turtle5.circle(5, 360, 8)
turtle5.end_fill()
time.sleep(1)
turtle5.clear()
There is turtle.ontimer() that calls a function with the specified delay:
turtle.ontimer(your_function, delay_in_milliseconds)
You need to put the part of the program you want to delay in its own thread, and then call sleep() in that thread.
I am not sure exactly what you are trying to do in your example, so here is a simple example:
import time
import threading
def print_time(msg):
print 'The time %s is: %s.' % (msg, time.ctime(time.time()))
class Wait(threading.Thread):
def __init__(self, seconds):
super(Wait, self).__init__()
self.seconds = seconds
def run(self):
time.sleep(self.seconds)
print_time('after waiting %d seconds' % self.seconds)
if __name__ == '__main__':
wait_thread = Wait(5)
wait_thread.start()
print_time('now')
Output:
The time now is: Mon Jan 12 01:57:59 2015.
The time after waiting 5 seconds is: Mon Jan 12 01:58:04 2015.
Notice that we started the thread that will wait 5 seconds first, but it did not block the print_time('now') call, rather it waited in the background.
EDIT:
From J.F. Sebastian's comment, the simpler solution with threading is:
import time
import threading
def print_time(msg):
print 'The time %s is: %s.' % (msg, time.ctime(time.time()))
if __name__ == '__main__':
t = threading.Timer(5, print_time, args = ['after 5 seconds'])
t.start()
print_time('now')
Related
i need to check data on an API. The API is refreshed with new data every 5 minutes (10:00, 10:05, 10:10 etc...)
I don't want to use time.sleep(300) because i want my script to do something at 10:05:03, then 10:05:03 etc. and not 5 min avec the script started (maybe it started at 10h12
How can i build this?
Thanks y'all.
UPDATE:
Just wanted to remove the possibility of recursion error, so I have rewritten the code:
from threading import Thread
from time import sleep
import datetime
def check_api():
# ... your code here ...
pass
def schedule_api():
while datetime.datetime.now().minute % 5 != 0:
sleep(1)
check_api()
while True:
sleep(300)
check_api()
thread = Thread(target=schedule_api)
thread.start()
Also if you want your thread to quit when the main program exits you could set daemon as True on the thread like:
thread.daemon = True
But this does not enforce a clean termination of this thread so you could also try this approach below:
# ...
RUNNING = True
# ...
thread = Thread(target=schedule_api)
thread.start()
#...
def main():
# ... all main code ...
pass
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
RUNNING = False
You can use the following code:
import threading
def check_api():
pass
timer_thread = threading.Timer(300, check_api)
timer_thread.start()
# call timer_thread.cancel() when you need it to stop
This will call your check_api function every 5 minutes and will not block your main code's execution.
as mentioned by #scotyy3785 the above code will only run once but I realize what you want and have written the code for it:
from threading import Thread
from time import sleep
import datetime
def check_api():
# ... your code here ...
pass
def caller(callback_func, first=True):
if first:
while not datetime.datetime.now().minute % 5 == 0:
sleep(1)
callback_func()
sleep(300)
caller(callback_func, False)
thread = Thread(target=caller, args=(check_api,))
thread.start()
# you'll have to handle the still running thread on exit
The above code will call check_api at minutes like 00, 05, 10, 15...
Check the time regularly in a loop and do something at certain minute marks:
import time
# returns the next 5 minute mark
# e.g. at minute 2 return 5
def get_next_time():
minute = time.localtime().tm_min
result = 5 - (minute % 5) + minute
if result == 60:
result = 0
return result
next_run = get_next_time()
while True:
now = time.localtime()
# at minute 0, 5, 10... + 3 seconds:
if next_run == now.tm_min and now.tm_sec >= 3:
print("checking api")
next_run = get_next_time()
time.sleep(1)
I'm making a simple client/server program in Python 3 and in the client I would like a clock or printout of the running time. I'm trying to make it in a loop that starts at the beginning of the program, but in a thread so the rest of the code keeps going.
class time_thread():
def run(self):
loop = 0
while (zetime > -1):
print(zetime);
zetime = zetime + 1;
time_thread.start()
zetime = 0
This is what I have so far, but it doesn't work. It says:
time_thread has no attribute start()
I'm new to this and haven't used threads before, so I'm not sure how to go about this. Is there a better way?
I think this is what you're looking for:
import time, sys
zetime = 0
while (zetime > -1):
sys.stdout.write("\r" + str(zetime))
sys.stdout.flush()
time.sleep(1)
zetime = zetime + 1;
First of all , to use Thread module, you have to inherit the class Thread on your class, so you can use their methods like start.
To calculate time, you can use datetime.
from datetime import datetime
from time import sleep
start_time = datetime.now()
sleep(5) # code that you want to calculate.
end_time = datetime.now()
print(end_time - start_time)
Just place this
So let's say you define a function elapsed_time such as:
import time, sys
def elapsed_time(time_start):
''' time_start: a time.time()
Goal: print the elapsed time since time_start '''
# Allow to stop the counting once bool_time = False in the main program
global bool_elapsed_time
# loop while the condition
while bool_elapsed_time == True:
# Note: erase and write below does not work in spyder but in a shell yes
print ("Elapsed time: {} seconds".format(int(time.time() - time_start))),
sys.stdout.flush()
print ("\r"),
time.sleep(1)
# erase the line with elapsed time to clean the shell at the end
sys.stdout.flush()
print ("\r"),
Then in your program:
import threading
bool_elapsed_time = True
t = threading.Thread(name='child procs', target=elapsed_time, args=(time.time(),))
t.start()
## Here add the job you want to do as an example:
time.sleep(10)
bool_elapsed_time = False #to stop the elapsed time printing
Should do the job you want to do.
Note: I used python 2.7 so it might be slightly different with 3.x
So I currently have python printing how long it took for a function to run after its done running with something like:
import time
t = time.time()
# do something in here
print "\n Time Taken: %.3f sec" % (time.time()-t)
but I want to show the live time that has passed since the function has started, and I cant quite figure out a way to get that to happen.
for example in a terminal I want it to say something like:
Working on xFunction. Time Elapsed 72.485 sec... (live updated time)
xFunction Has finished.
Time Taken: 1152.546 sec
Any help would be appreciated.
Here's an example with a thread that will print how much time has elapsed since it started and can be stopped from the main loop.
import time
import threading
class ElapsedTimeThread(threading.Thread):
""""Stoppable thread that prints the time elapsed"""
def __init__(self):
super(ElapsedTimeThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def run(self):
thread_start = time.time()
while not self.stopped():
print("\rElapsed Time {:.3f} seconds".format(time.time()-thread_start), end="")
#include a delay here so the thread doesn't uselessly thrash the CPU
time.sleep(0.01)
if __name__ == "__main__":
start = time.time()
thread = ElapsedTimeThread()
thread.start()
# do something
time.sleep(5)
# something is finished so stop the thread
thread.stop()
thread.join()
print() # empty print() to output a newline
print("Finished in {:.3f} seconds".format(time.time()-start))
This gives the following output, with the Elapsed Time counting up from zero and being overwritten:
J:\>python thr_time.py
Elapsed Time 5.000 seconds
Finished in 5.001 seconds
Note that this code is in Python 3. More info on stopping threads here & here.
Let me know if you'd like clarification on any portions.
I've modified #import_random 's code to enable the ability to probe elapsed time at any time during the execution of code, by wrapping 2 functions for initialization and finalization of ETC:
import time
import threading
class ElapsedTimeThread(threading.Thread):
""""Stoppable thread that prints the time elapsed"""
def __init__(self):
super(ElapsedTimeThread, self).__init__()
self._stop_event = threading.Event()
self.thread_start = time.time()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def getStart(self):
return self.thread_start
def getCurrentTime(self):
print("\rElapsed Time {:.3f} s. ".format(time.time()-self.thread_start), end="", flush=True )
def run(self):
self.thread_start = time.time()
while not self.stopped():
print("\rElapsed Time {:.3f} s. ".format(time.time()-self.thread_start), end="", flush=True)
#include a delay here so the thread doesn't uselessly thrash the CPU
time.sleep(0.01)
def startTimeCounter():
threadTimer = ElapsedTimeThread()
threadTimer.start()
return threadTimer
def stopTimeCounter(threadTimeCounter):
print() # empty print() to output a newline
print("Finished in {:.3f} s. ".format(time.time()-threadTimeCounter.getStart()))
threadTimeCounter.stop()
threadTimeCounter.join()
Let's say I have the following python3 program:
from threading import Timer
import time
thread = Timer(600, print, args=['I am running'])
thread.start()
while threading.activeCount() > 1:
{{Function to calculate time until thread will start running}}
print ("Thread will start in %d seconds" % {get above value})
time.sleep(10)
What I'm looking at is a little more complex, with multiple threads, but essentially, for a given Timer thread, is there any way to inspect it to see when it is scheduled to run?
I'm not sure I'm getting what you say right, but you may want something like that:
from threading import Thread
import time
thread = Timer(600, print, args=['I am running'])
thread.start()
class ThreadTimeoutLauncher(Thread):
def __init__(self, timeout, cb, *args, **kwarg):
super(Thread, self).__init__()
self.timeout = timeout
self._cb = cb
self._args = args
self._kwarg = kwarg
def run():
print ("Thread will start in %d seconds" % self.timeout)
while self.timeout > 0:
time.sleep(1)
self.timeout -= 1
self.cb(*self._args, **self._kwarg)
the idea here, is to recreate a Timer thread that will count down until the time is out, and updates the "timeout value" while doing so. When it's over it launches the Thread event. So when you do:
def foo():
print "Thread launched!"
t = ThreadTimeoutLauncher(600, foo)
t.start()
while True:
time.sleep(0.5)
print "thread will be launched in: %d sec." % t.timeout
It may also be possible to inherit from Timer and change the run() method of Timer, but it'd mean to UTSL ;-)
I would like 3 Threads in Python to run for n seconds. I want to start them all at the same time and have them finish at the same time (within milliseconds). How do I do this?
threading.Timer only starts after the previous one has been completed.
import threading
import time
class A(threading.Thread):
def run(self):
print "here", time.time()
time.sleep(10)
print "there", time.time()
if __name__=="__main__":
for i in range(3):
a = A()
a.start()
prints:
here 1279553593.49
here 1279553593.49
here 1279553593.49
there 1279553603.5
there 1279553603.5
there 1279553603.5