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()
Is there any real difference between these two?
Variables are accessed in the threaded function, but not passed to it through Thread(args)
Variables are passed to the threaded function through Thread(args)
# 1
def do_something():
event = Event()
tracker = MyObject.instance()
start_time = datetime.timestamp(datetime.now())
def threaded_function():
current_time = datetime.timestamp(datetime.now())
while True:
if current_time - start_time > 30:
tracker.put("too long")
break
elif event.is_set():
break
else:
time.sleep(1)
thread = Thread(target=threaded_function)
thread.start()
# Do something that may take more than 30 seconds
event.set()
# 2
def do_something():
event = Event()
def threaded_function(tracker, start_time):
current_time = datetime.timestamp(datetime.now())
while True:
if current_time - start_time > 30:
tracker.put("too long")
break
elif event.is_set():
break
else:
time.sleep(1)
tracker = MyTracker.instance()
start_time = datetime.timestamp(datetime.now())
thread = Thread(target=threaded_function, args=(tracker, start_time))
thread.start()
# Do something that may take more than 30 seconds
event.set()
Practically speaking, there is little difference between the two, since you only start one thread.
In #1, threaded_function is a closure over two local variables in do_something. There would be no way to reliably vary those values between two or more threads, as any change to tracker or start_time would be visible inside any call to do_something.
In #2, tracker and start_time are local to threaded_function. They can be initialized to different values in each thread that runs threaded_function, and the values in one function are independent of values in another.
I trying to create a timer for my quiz game. It should reset after every right question. But problem with my code is that it keeps increasing speed after every time it resets.
timeCount = 30
def countdown():
global timeCount
while timeCount > 0:
print(timeCount)
sleep(1)
timeCount -= 1
else:
print("Time Out!")
I think this is what you are trying to do:
import time
timeCount = 30
start = time.time()
seconds = 0
def countdown():
global timeCount
global seconds
while seconds < timeCount:
now = time.time()
seconds = now - start
print(timeCount - seconds)
else:
print("Time Out!")
countdown()
This teaches you how to use time.time. You can take away seconds from timeCount to make a timer that goes down from 30 to 0. When the seconds hits 30, you can end the loop and print "Time out". You can truncate the unnecessary floating point values, since i am assuming floating point numbers doesn't look good on a quiz timer and is unnecessary as well.
seconds = int(seconds)
You can use the function time.perf_counter() :
import time
start=time.perf_counter()
time.sleep(1) #you can replace the sleep function with the action you want to monitor
end=time.perf_counter()
print('elapsed time : ',end-start)
In the example above, time.perf_counter() evaluated the time when it is called so it gives you the elapsed time between the two call.
if you want to use your current logic :
Your 'global' statement means that your are going to modify the 'timeCount' variable during the execution of your code. To fix it, you can use a new local variable in your function (called 'local_count' in the below solution), like this you reset the countdown each time you call your function :
import time
timeCount = 30
def countdown():
local_count = timeCount
while local_count > 0:
print(local_count)
time.sleep(1)
local_count -= 1
print("Time Out!")
I have a code with this ↓ part in it, which should do something when the time and day come. It has outer and inner time and day checks (while loops).
Outer for the situation in which code starts processing in time (or day) which is not in the timerange for code processing - it should wait until that time (or day). And it works, but only in situation when I set it like 10 minutes before the timerange (code processing time). When I set it like a night before, it won't works and it stops in print("timerange wait") It shows False even it should be True. Is there a problem because it is not in the same day? Or something else? Please give me some advices.
Here is the simple version of code (without unnecessary parts )
import os
import datetime
from time import sleep
from datetime import date
#setting used variables
now = datetime.datetime.now()
morning = now.replace(hour=8, minute=0, second=0, microsecond=0)
evening = now.replace(hour=18, minute=9, second=0, microsecond=0)
# function for check creating "timerange -start time, end time"
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
# main program for doing something
def main():
while True:
# Time period check - Check if time and weekdays are not out of range
# if not in range will wait till the time
if date.today().weekday():
dayz = True
else:
dayz = False
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True:
print("waiting for function-time")
sleep(10)
continue
if dayz != True:
print("waiting for function-days")
sleep(3600)
continue
while True:
print("do something")
#check if during while loop there wasn't date, time change (out of timerange etc)
if date.today().weekday():
dayz = True
else:
dayz = False
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True:
print("break inner loop-timerange")
break
if dayz != True:
print("break inner loop-dayz")
break
print("do something -main work")
#program starts here
timerange = time_in_range(morning, evening, now)
# check if today is weekday (outer loop)
if date.today().weekday():
dayz = True
else:
dayz = False
# if today is not a weekday wait till weekday (outer loop)
#for situation where the code started not in weekday
while dayz != True:
print("days wait")
sleep(3600)
dayz = date.today().weekday()
if dayz == True:
break
# If it is not processing time, wait until it becomes
# for the situation where code started not in "timerange"
while timerange != True:
print("timerange wait") # ---------HERE IT STOPS---------
# But it works fine, when I set it like one hour before 'timerange' or so...
sleep(10)
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
print(timerange)
if timerange == True:
break
# Do the main function
main()
# Let know when code ends
print("Over of Code")
import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box, The dialog box is not the problem. But my minutes variable does not increment in this code.
See Timer Objects from threading.
How about
from threading import Timer
def timeout():
print("Game over")
# duration is in seconds
t = Timer(20 * 60, timeout)
t.start()
# wait for time completion
t.join()
Should you want pass arguments to the timeout function, you can give them in the timer constructor:
def timeout(foo, bar=None):
print('The arguments were: foo: {}, bar: {}'.format(foo, bar))
t = Timer(20 * 60, timeout, args=['something'], kwargs={'bar': 'else'})
Or you can use functools.partial to create a bound function, or you can pass in an instance-bound method.
You can really simplify this whole program by using time.sleep:
import time
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
# Loop until we reach 20 minutes running
while mins != 20:
print(">>>>>>>>>>>>>>>>>>>>> {}".format(mins))
# Sleep for a minute
time.sleep(60)
# Increment the minute total
mins += 1
# Bring up the dialog box here
I'd use a timedelta object.
from datetime import datetime, timedelta
...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
if next_time <= datetime.now():
minutes += 1
next_time += period
Your code's perfect except that you must do the following replacement:
minutes += 1 #instead of mins = minutes + 1
or
minutes = minutes + 1 #instead of mins = minutes + 1
but here's another solution to this problem:
def wait(time_in_seconds):
time.sleep(time_in_seconds) #here it would be 1200 seconds (20 mins)
mins = minutes + 1
should be
minutes = minutes + 1
Also,
minutes = 0
needs to be outside of the while loop.
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box.
All you need is to sleep the specified time. time.sleep() takes seconds to sleep, so 20 * 60 is 20 minutes.
import time
run = raw_input("Start? > ")
time.sleep(20 * 60)
your_code_to_bring_up_dialog_box()
# this is kind of timer, stop after the input minute run out.
import time
min=int(input('>>'))
while min>0:
print min
time.sleep(60) # every minute
min-=1 # take one minute
import time
...
def stopwatch(mins):
# complete this whole code in some mins.
time.sleep(60*mins)
...
import time
mintt=input("How many seconds you want to time?:")
timer=int(mintt)
while (timer != 0 ):
timer=timer-1
time.sleep(1)
print(timer)
This work very good to time seconds.
You're probably looking for a Timer object: http://docs.python.org/2/library/threading.html#timer-objects
Try having your while loop like this:
minutes = 0
while run == "start":
current_sec = timer()
#print current_sec
if current_sec == 59:
minutes = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
import time
def timer(n):
while n!=0:
n=n-1
time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
print "00 : ",n
timer(30) #here you can change n according to your requirement.
import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I was actually looking for a timer myself and your code seems to work, the probable reason for your minutes not being counted is that when you say that
minutes = 0
and then
mins = minutes + 1
it is the same as saying
mins = 0 + 1
I'm betting that every time you print mins it shows you "1" because of what i just explained, "0+1" will always result in "1".
What you have to do first is place your
minutes = 0
declaration outside of your while loop. After that you can delete the
mins = minutes + 1
line because you don't really need another variable in this case, just replace it with
minutes = minutes + 1
That way minutes will start off with a value of "0", receive the new value of "0+1", receive the new value of "1+1", receive the new value of "2+1", etc.
I realize that a lot of people answered it already but i thought it would help out more, learning wise, if you could see where you made a mistake and try to fix it.Hope it helped. Also, thanks for the timer.
from datetime import datetime
now=datetime.now()
Sec=-1
sec=now.strftime("%S")
SEC=0
while True:
SEC=int(SEC)
sec=int(sec)
now=datetime.now()
sec=now.strftime("%S")
if SEC<sec:
Sec+=1
SEC=sec
print(Sec) #the timer is Sec