I\'m trying to ucreate a timer function that runs in the background of my code and make it so I can use/check the time. What I mean by use/check, I\'m trying to make it so I can
import time
def timer(tim):
time.sleep(1)
print tim
def hall():
tim = 15
while (tim > 0):
print 'do something'
timer(tim)
tim-=1
Not the cleanest solution, but it will do what you need.
The way you do it, you'll going to have to use multithread.
Here is another, simpler approach :
On your script beginning, set a time_start
variable with the number of seconds since the epoch using time.time()
Then when you need the number of elapsed seconds, use time.time() - time_start
:
t_start = time.time()
# do whatever you'd like
t_current = int(time.time()-t_start) # this way you get the number of seconds elapsed since start.
You can put that in a function as well, defining t_start as a global variable.
import time
t_start = time.time()
def timer():
global t_start
print(str(int(time.time()-t_start)))
print('start')
time.sleep(2)
timer()
time.sleep(3)
timer()
The problem with your code is that when you run hall()
, Python first executes the whole of timer()
(i.e. the whole for
loop), and then moves on with the rest of the code (it can only do one thing at a time). Thus, by the time it reaches the while
loop in hall()
, timer
is already 0
.
So, you're going to have to do something about that timer
so that it counts down once, and then it moves on to the do something
part.
Something that you can do is this:
def hall():
for a in range(0, 15):
print(15 - a)
# do something
time.sleep(1)
This should work just fine (if you're only executing hall
15 times), and condenses your code to just one function.