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.

4
  • 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 Commented Aug 23, 2013 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? Commented Aug 23, 2013 at 15:30
  • Just a pop up at the end of probably 15 minutes that i'll set Commented Aug 23, 2013 at 15:33
  • here's how to call a function with a delay using different libraries: Tkinter, Twisted, Asyncio, Gtk Commented Oct 28, 2014 at 9:19

14 Answers 14

70

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.

Sign up to request clarification or add additional context in comments.

8 Comments

why do i need the "time.sleep(1500)"
it is an example so that your main does not drop out right away :D
In gui application you would just continue your mainloop.
OKay, so your code means when t is started it executes anything in the timeout function in that time interval?
the timeout function is executed once after 20 minutes.
|
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

6 Comments

What does time.sleep do?
@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".
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ϟ - 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.
@Qwertieϟ - Use Timer objects for that. Or the threading library in general.
|
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

2 Comments

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.
Definitely. 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."
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)

Comments

1
mins = minutes + 1

should be

minutes = minutes + 1

Also,

minutes = 0

needs to be outside of the while loop.

2 Comments

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.
How about minutes += 1?
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()

Comments

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 

1 Comment

hope my poor language would be helpful
1
import time 

...

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

...

Comments

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.

Comments

0

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

1 Comment

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

Comments

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.

Comments

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.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.