How to get return value in timer - python

i made simple timer
this timer has two function
1.countdown 2. stopwatch
btw i want to use timer in game
ex) countdown stop > game finish
So i want return value in timer..
but i can't
plz help me :)
import time
import threading
count = 0
def start_timer(count):
print(count)
count -= 1
timer = threading.Timer(1, start_timer, args=[count])
timer.start()
if count == 0:
print("game start!")
timer.cancel()
def stop_watch():
now = time.time()
check = input("press button\n")
stop = time.time()
print("time : %0.3f" % (stop - now))
i can't get return value

Related

should i use for loop or while loop to make a break timer in python?

I have this code to stop a function at a specific time. I would loop through the function and then break the function, if it takes too long, is there a better way to do it?
import time
def function_one()
rec = (time.time())
print("im starting")
ans = str(time.time() - rec)
ans = (round(float(ans), 15))
print("this is where im doing something code")
while ans < 10:
return function_one()
break
You can make it simpler like this:
import time
def function_one():
start_time = time.time()
while True:
print('Function doing something ...')
if time.time() - start_time > 10:
break
function_one()
Here, I'm using a while loop just to keep the function running, but that depends on the details of your function.
In general, what you need is:
set the start time
do whatever the function is supposed to be doing;
check if it's been running for too long and, in case it has, you can simply return.
So, something like:
import time
def function_one():
start_time = time.time()
# do your job
if time.time() - start_time > 10:
return something
function_one()
If you want to stop a function after a set amount of time has passed I would use a while loop and do something like this.
import time
def function_one():
start = (time.time()) #start time
limit = 1 #time limit
print("im starting")
while (time.time() - start) < limit:
#input code to do here
pass
print(f"finished after {time.time() - start} seconds")
function_one()

How to create a Python timer to count down?

My code:
def timer():
while True:
try:
when_to_stop = 90
except KeyboardInterrupt:
break
except:
print("error, please star game again")
while when_to_stop > 0:
m, s = divmod(when_to_stop, 60)
h, m = divmod(m, 60)
time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" +
str(s).zfill(2) # got cut off, belongs to the line before this
print("time:", time_left + "\r", end="")
if time_left == 0:
print("TIME IS UP!")
time.sleep(1)
when_to_stop -= 1
This works perfectly fine, except that time.sleep means my whole program sleeps, so anything after that while stop for 90 seconds. Any way to fix that?(or make a new timer without time.sleep?)
I think that, alternatively, you could keep track of when the timer starts, and check the time by seeing if the time that's passed is longer than the timer is supposed to last. I'm not sure how much you know about classes and objects in Python, but here is the solution that came to mind:
import datetime
class Timer:
def __init__(self,**kwargs):
self.start = datetime.datetime.now()
self.length = datetime.timedelta(**kwargs)
self.end = self.start+self.length
def isDone(self):
return (self.end-datetime.datetime.now()).total_seconds()<=0
def timeLeft(self):
return self.end-datetime.datetime.now()
def timeElapsed(self):
return datetime.datetime.now()-self.start
Even if you don't quite understand the class itself, if you put it in your code it should work like a charm:
#This has the same options as:
#class datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
t = Timer(days=2)
while(not t.isDone()):
#Do other game stuff here....
time_left = t.timeLeft()
print(f"time: {time_left}")
#And here....
print("Done now")

Error while making timer using python ( invalid literal for int() with base 10 )

I was trying to make a timer using python but when i run that code i get stuck with it .
This is my code.
import os
import time
while True:
timer = input("enter the time when to stop the timer = ")
if "second" in timer or "seconds"in timer:
t= timer.replace("second","").replace("seconds","")
elif "minutes" in timer or "minute" in timer:
t=timer.replace("minutes",'*60').replace("minute",'*60')
elif "hour" in timer or "hours" in timer:
t= timer.replace("hour","*60*60").replace("hours","60*60")
elif "hour" in timer or "hours" in timer and "minutes" in timer or "minute" in timer:
t=timer.replace("hour","*60*60").replace("hours","60*60").replace("and","+").replace("minutes","*60").replace("minute","*60")
else:
print("write valid number")
when_to_stop =abs(int(t))
while when_to_stop >0:
os.system('cls')
m,s = divmod(when_to_stop,60)
h,m = divmod(m,60)
print("\n\n\n\n\n\n\n\n\n")
print("\t\t\t\t|"+str(h).zfill(2)+":" + str(m).zfill(2)+":"+str(s).zfill(2)+"|")
time.sleep(1)
when_to_stop -=1
print()
print("\t\t\t\tTIME OUT")
exit()
when i run it with giving the value 10 minutes it shows the error and this code run properly only when i use 10 second.
enter the time when to stop the timer = 10 minutes
Traceback (most recent call last):
File "E:\mycodes\python codes\testcode.py", line 35, in <module>
when_to_stop =abs(int(t))
ValueError: invalid literal for int() with base 10: '10 *60'
please solve this error
You are trying to convert the '10 *60' string to an integer. If you place print(t) inside of every condition for testing you can see that when the code gets to:
when_to_stop =abs(int(t))
t is equal to a string that cannot be converted to an integer.
Instead of using replace, you can simply keep the conditional structure but then strip the string to just the integer and multiply it as necessary.
import re
timer = input("enter the time when to stop the timer = ")
if "second" in timer or "seconds"in timer:
t = re.findall(r'\d+', timer) # this returns a list containing the integer like so ['10'] for '10 seconds'
Here is the full part of your first loop:
while True:
timer = input("enter the time when to stop the timer = ")
if "second" in timer or "seconds"in timer:
t = re.findall(r'\d+', timer)
totalTime = t[0]
elif "minutes" in timer or "minute" in timer:
t = re.findall(r'\d+', timer)
totalTime = t[0] * 60
elif "hour" in timer or "hours" in timer:
t = re.findall(r'\d+', timer)
totalTime = t[0] * 60 * 60
elif "hour" in timer or "hours" in timer and "minutes" in timer or "minute" in timer:
t = re.findall(r'\d+', timer)
totalTime = (t[0] * 60 * 60) + (t[1] * 60)
else:
print("write valid number")
totalTime will therefore be the total time in seconds. I ran this and it works but displaying the time in hours is not working but minutes and seconds are. This is a separate issue of how you are processing the totalTime seconds to display the counter counting down.
According to the tests I ran this code should be fully functional - let me know if it doesn't work for you.
import os
import time
import re
while True:
timer = input("enter the time when to stop the timer = ")
if "second" in timer or "seconds"in timer:
filtering = re.findall(r'\d+', timer)
timer = int(''.join(filtering))
elif ('minutes' not in timer and "minute" not in timer) and ("hour" in timer or "hours" in timer):
filtering = re.findall(r'\d+', timer)
timer = int(''.join(filtering))*3600
elif ("hour" in timer or "hours" in timer) and ("minutes" in timer or "minute" in timer):
print('hello')
filtering = re.findall(r'\d+', timer)
a=(int(''.join(filtering[0]))*3600)
b=(int(''.join(filtering[1]))*60)
timer =a+b
elif "minutes" in timer or "minute" in timer:
filtering = re.findall(r'\d+', timer)
timer = int(''.join(filtering))*60
else:
print("Please! write valid number")
when_to_stop =abs(int(timer))
while when_to_stop >0:
os.system('cls')
m,s = divmod(when_to_stop,60)
h,m = divmod(m,60)
print("\t\t\t\t|"+str(h).zfill(2)+":" + str(m).zfill(2)+":"+str(s).zfill(2)+"|")
time.sleep(1)
when_to_stop -=1
print()
print("\t\t\t\tTIME OUT")
exit()
I have solved the problem of my code but i have still a problem.
when i run the code by giving the value of 1 hour and 15 minute it start with wrong time else it work fine .
import os
import time
import re
while True:
timer = input("enter the time when to stop the timer = ")
if "second" in timer or "seconds"in timer:
filtering = re.findall(r'\d+', timer)
timer = int(''.join(filtering))
elif "minutes" in timer or "minute" in timer:
filtering = re.findall(r'\d+', timer)
timer = int(''.join(filtering))*60
elif "hour" in timer or "hours" in timer:
filtering = re.findall(r'\d+', timer)
timer = int(''.join(filtering))*3600
elif "hour" in timer or "hours" in timer and "minutes" in timer or "minute" in timer:
filtering = re.findall(r'\d+', timer)
a=(int(''.join(filtering[0]))*3600)
b=(int(''.join(filtering[1]))*60)
timer =a+b
else:
print("Please! write valid number")
when_to_stop =abs(int(timer))
while when_to_stop >0:
os.system('cls')
m,s = divmod(when_to_stop,60)
h,m = divmod(m,60)
print("\n\n\n\n\n\n\n\n\n")
print("\t\t\t\t|"+str(h).zfill(2)+":" + str(m).zfill(2)+":"+str(s).zfill(2)+"|")
time.sleep(1)
when_to_stop -=1
print()
print("\t\t\t\tTIME OUT")
exit()

Stop the program execution after some time interval

I have the following code and I want to stop the program if the condition is not true for a certain period of time. Suppose the condition (sum>99999) is false for a period of 10 seconds, then this program stops and gives present sum values. I am on Windows. Any idea how to do it in Windows.
for j in i:
sum=sum+A[j]
if(sum>99999):
print("Current sum is",sum)
This should accomplish what you're describing.
import time
import sys
start_time = time.time()
for j in i:
sum = sum + A[j]
if sum > 99999:
print("Current sum is ", sum)
start_time = time.time() # reset timer if the condition becomes true
elif time.time() - start_time >= 10:
print("Current sum is ", sum)
sys.exit()
Try this:
import time
import sys
start = time.time()
for j in i:
sum += A[j]
if sum > 99999:
print(sum)
elif time.time() - start > 10:
print(sum)
break # if you just want to exit the loop or sys.exit() if you want to exit the program
Sometimes an iteration is heavy enough to render technique proposed by other answers pretty useless. If you don't have access to break execution upon condition, this or that recipes would be helpful.
I will copy the simpler one (and the one I prefer in my code):
import threading
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result
import sys
import time
start_time = time.time()
time_limit = 2
if (comdition):
if((time.time() - start_time) > time_limit):
sys.exit()
else:
#more stuff here

Python realtime timer

Could anybody advise me on converting the Java Timer class to Python? Currently I am converting a Java program to a Python script. However, Python does not have the Timer/TimerTask library (if it does have this, please enlighten me. Thanks!). I need to be able to reset the Timer. Java has Timer.cancel, but Python doesn't have this. Is there any replacement for it?
timer.cancel();
timer = new Timer("Printer");
MyTask t = new MyTask();
timer.schedule(t, 0, 1000);
Java script timer
class Timerclass extends TimerTask {
//times member represent calling times.
private int times = 0;
public void run() {
times++;
if (times <= 5) {
System.out.println(""+times);
} else {
this.cancel();
//Stop Timer.
System.out.println("Timer Finish");
}
}
}
Currently my code
import time
import threading
class Variable:
count = 0
people = 0
times = 0
def enter():
if int(Variable.count == 1):
print("Entered")
t = threading.Timer(5.0, countdown)
t.start()
else:
print("Entered +1")
t.clear() // Stuck Help
t = threading.Timer(5.0, countdown)
t.start()
def out():
if int(Variable.count > 0):
print("Exited")
elif int(Variable.count < 0):
print("Error")
def countdown():
print("TIMEUP")
while True:
sensor1 = input("Sensor 1: ")
sensor2 = input("Sensor 2: ")
Variable.count+=1
if int(sensor1) == int(sensor2):
Variable.count -= 1
print(Variable.count)
print("error")
elif int(sensor1) == 1:
Variable.people += 1
print(Variable.people)
enter()
elif int(sensor2) == 1:
Variable.people -= 1
print(Variable.people)
out()
else:
print("Error")
i have one problems that i'm stuck in i need to stop the current counting and start a new one whenever the method call
Basically what i want or im looking out for is when i recall this method it will reset or cancel any existing and recount again
Update latest
import time
import threading
class Variable:
count = 0
people = 0
times = 0
def countdown():
print("TIMEUP")
t = threading.Timer(5.0, countdown)
def enter():
if int(Variable.count == 1):
print("Entered")
t.start()
else:
print("Entered +1")
t.cancel()
t.join() # here you block the main thread until the timer is completely stopped
t.start()
def out():
if int(Variable.count > 0):
print("Exited")
elif int(Variable.count < 0):
print("Error")
while True:
sensor1 = input("Sensor 1: ")
sensor2 = input("Sensor 2: ")
Variable.count+=1
if int(sensor1) == int(sensor2):
Variable.count -= 1
print(Variable.count)
print("error")
elif int(sensor1) == 1:
Variable.people += 1
print(Variable.people)
enter()
elif int(sensor2) == 1:
Variable.people -= 1
print(Variable.people)
out()
else:
print("Error")
Anybody can spot my ,istake im getting this error but i t.clear() the process
in start raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
I would suggest using the time module for something like this:
from time import time, sleep
from datetime import datetime, timedelta
nowtime = time()
#Put your script here
x = 1
for k in range(1000):
x+=1
sleep(0.01)
sec = timedelta(seconds=int(time()-nowtime))
d = datetime(1,1,1)+sec
print("DAYS:HOURS:MIN:SEC")
print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))
This assigns the time in seconds at the beginning to a variable, and after the main script has finished, it subtracts the previous time from the current time and formats it in days, hours, minutes, and seconds.
Here is it running:
bash-3.2$ python timing.py
DAYS:HOURS:MIN:SEC
0:0:0:10
bash-3.2$
You could also use the Threading module, which has a built-in cancel method:
>>> import threading
>>> def hello():
... print "This will print after a desired period of time"
...
>>> timer = threading.Timer(3.0, hello)
>>> timer.start() #After 3.0 seconds, "This will print after a desired period of time" will be printed
>>> This will print after a desired period of time
>>> timer.start()
>>> timer = threading.Timer(3.0, hello)
>>> timer.start()
>>> timer.cancel()
>>>
Python actually has a class for this, which includes a cancel method: threading.Timer. It seems to be close enough to the Java Timer class for your needs (The Java Timer also runs in background thread). Here's the example usage from the docs:
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
Edit:
The problem with your updated code is that you're trying to use the same Timer object more than once. That may be possible in the Java implementation, but in Python you can't reuse a Thread object (Timer is a Thread subclass). You'll need to create a new Timer object after you join() it. Like this:
t = threading.Timer(5.0, countdown)
def enter():
global t # You need this to tell Python that you're going to change the global t variable. If you don't do this, using 't = ..' will just create a local t variable.
if int(Variable.count == 1):
print("Entered")
t.start()
else:
print("Entered +1")
t.cancel()
t.join() # here you block the main thread until the timer is completely stopped
t = threading.Timer(5.0, countdown)
t.start()

Categories