39
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.

user2711485
  • 429
  • 1
  • 4
  • 5
  • Hey Guys, I don't think my question is been answered The concept is to write a code that pops up a dialog box after some specified that time – user2711485 Aug 23 '13 at 15:24
  • Your code attempts to print a timer tick every minute. Do you want the final code to do that, or just pop up a dialog box? – tdelaney Aug 23 '13 at 15:30
  • Just a pop up at the end of probably 15 minutes that i'll set – user2711485 Aug 23 '13 at 15:33
  • here's [how to call a function with a delay using different libraries: Tkinter, Twisted, Asyncio, Gtk](http://stackoverflow.com/a/14040516/4279) – jfs Oct 28 '14 at 09:19

14 Answers14

69

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.

Antony Thomas
  • 3,576
  • 2
  • 34
  • 40
31

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
phoenix
  • 7,988
  • 6
  • 39
  • 45
  • 1
    What does time.sleep do? – user2711485 Aug 23 '13 at 15:15
  • @user2711485 - It suspends the computer for however many seconds you tell it (in this case 60, which is a minute). In other words, it is saying "do nothing until this time runs out". –  Aug 23 '13 at 15:17
  • 1
    Is it possible to have other code running while using time.sleep() eg if you were making a game could the timer run in the background or would everything stop when time.sleep() is called? – Qwertie Jul 11 '14 at 03:59
  • 1
    @Qwertieϟ - Everything would be suspended until the call to `time.sleep` finished. That is the purpose of `time.sleep`: to stop program execution for a certain period of time. –  Jul 11 '14 at 14:20
  • 2
    @Qwertieϟ - Use [Timer objects](https://docs.python.org/2/library/threading.html#timer-objects) for that. Or the [threading](https://docs.python.org/2/library/threading.html) library in general. – Poik Sep 02 '14 at 18:46
  • What is raw_input. I get-> NameError: name 'raw_input' is not defined – uplearned.com Aug 05 '19 at 10:24
7

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
Silas Ray
  • 25,682
  • 5
  • 48
  • 63
  • 3
    While this works, constantly running while loops can consume a lot of processing power. Adding a sleep period (even only a second) can greatly reduce that usage. – Russia Must Remove Putin Feb 02 '16 at 20:55
  • 2
    Definitely. [Busy waiting](https://en.wikipedia.org/wiki/Busy_waiting) loops are "considered an anti-pattern and should be avoided, as processor time that could be used to execute a different task is instead wasted on useless activity." – martineau Jul 18 '16 at 13:55
2

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)
Anshu Dwibhashi
  • 4,617
  • 3
  • 28
  • 59
1
mins = minutes + 1

should be

minutes = minutes + 1

Also,

minutes = 0

needs to be outside of the while loop.

David
  • 105
  • 1
  • 7
  • 1
    Also, `minutes = 0` needs to be outside of the `while` loop if you are going to stick with this code. But really, he should probably just use something better suited to the task. – Silas Ray Aug 23 '13 at 15:13
  • How about `minutes += 1`? – Lanaru Aug 23 '13 at 15:19
1

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()
tdelaney
  • 73,364
  • 6
  • 83
  • 116
1
# 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 
Karrar Ali
  • 69
  • 1
  • 7
1
import time 

...

def stopwatch(mins):
   # complete this whole code in some mins.
   time.sleep(60*mins)

...
tortue
  • 113
  • 5
1
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.

0

You're probably looking for a Timer object: http://docs.python.org/2/library/threading.html#timer-objects

lmjohns3
  • 7,422
  • 5
  • 36
  • 56
  • Using a timer object could get tricky if the action it triggers is non-trivial. You have to deal with thread synchronization issues if you use a timer. – Silas Ray Aug 23 '13 at 15:15
0

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
m-oliv
  • 419
  • 11
  • 27
0
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.
CDspace
  • 2,639
  • 18
  • 30
  • 36
shiva
  • 5,083
  • 5
  • 23
  • 42
0
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.

lider
  • 23
  • 6
0
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
CTH
  • 1
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 14 '22 at 00:26