- Creating a timer in python
- 14 Answers 14
- How to Perform Threading Timer in Python
- How to perform threading timer in Python
- Table of contents
- Prerequisites
- Python timer functions
- Instance 1
- Instance 2
- Threading module overview
- Creating and using the timer class
- Working with Python Decorator
- Importance of using Threads
- Conclusion
Creating a timer in python
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.
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
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?
14 Answers 14
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=)
Or you can use functools.partial to create a bound function, or you can pass in an instance-bound method.
OKay, so your code means when t is started it executes anything in the timeout function in that time interval?
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
@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.
from datetime import datetime, timedelta . period = timedelta(minutes=1) next_time = datetime.now() + period minutes = 0 while run == 'start': if next_time
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."
Your code's perfect except that you must do the following replacement:
minutes += 1 #instead of mins = minutes + 1
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)
needs to be outside of the while loop.
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.
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.
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.
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
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
declaration outside of your while loop. After that you can delete the
line because you don't really need another variable in this case, just replace it with
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.
How to Perform Threading Timer in Python
Threading allows multiple tasks to run concurrently. For example, when task A is running, I do not have to wait for it to complete. Meanwhile, tasks B, C will also be running. When the tasks are running simultaneously, they require multiple CPUs.
To run threads concurrently Python uses a technique known as task switching. As a result, Python switches between each task rapidly. Making it seems like multiple tasks are running in parallel, making it useful in event-driven tasks. The thread being lightweight, it requires less memory thereby saving on CPU resources.
How to perform threading timer in Python
A thread has an entry, an execution, and an exit point. The Python library contains a timer, a subclass of the “threading” class used for code execution after a limited period.
Threading in Python Timer() starts following the delay defined as an argument. The Timer class thus calls itself delaying the execution of the following operation by the same amount of time specified.
Table of contents
Prerequisites
To follow along the reader will need the following:
Python timer functions
After every specified number of seconds, a timer class function is called. start() is a function that is used to initialize a timer. To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class. The calling thread can be suspended for seconds using the function time.sleep(secs).
- To better understand this, I will be illustrating it with the use of a code snippet and also with the expected output inform of a screenshot.
Instance 1
## How class threading.Timer() in python works import threading as th ## Defining a method def sctn(): print("SECTION FOR LIFE \n") S = th.Timer(5.0, sctn) S.start() print("Exit Program\n")
Instance 2
In this second example, I will show you how to implement the suspend method cancel() , which we had seen earlier to end a thread.
##Illustrating the use of cancel() method in class Timer. import threading as th ## Defining of a method def sctn(): print("SECTION FOR LIFE \n") S = th.Timer(5.0, sctn) S.start() print("PROGRAM TERMINATION\n") S.cancel()
- When the program is executed, the line PROGRAM TERMINATION is displayed. This is because the object th.Timer gets canceled just before it has executed the “sctn” function.
- Below is the output of the above program:
Threading module overview
The latest threading module included with the current Python 2.4 provides a much more powerful and higher-level support for threads than the previous thread module.
The threading module exposes all the methods of the thread module and provides some additional functions as depicted below:
thread.activeCount() − Returns how many thread objects are active. thread.currentThread() − Returns how many thread objects in the caller's thread control. thread.enumerate() − Returns an overview list of all thread objects that are currently active.
Creating and using the timer class
The beauty of threading is that you can tell the computer to perform a task some other time or do it simultaneously. You can also execute the code simultaneously on different threads, making it extremely powerful. A timer class always runs in intervals.
The Python Timer class is used to perform an operation or have a function run after a specified period has passed. The threading class has a subclass called the class timer. In technical terms, we will create Timer objects when we need time-bound actions (methods), in technical terms.
To use Timer class we will first have to import the time module. The args parameter is always preferably used to declare arguments to the functions to be called.
##Timers ##Execute code at timed intervals ##Imports and Displays import time from threading import Timer def display(msg): print(msg + ' ' + time.strftime('%H:%M:%S')) ##Basic timer def run_once(): display('run_once:') t=Timer(10,display,['Timeout:']) t.start()#Here run is called run_once() ##Runs immediately and once print('Waiting. ') ##Lets make our timer run in intervals ##Put it into a class ##Making it run until we stop it ##Just getting crazy.Notice We have multiple timers at once! class RepeatTimer(Timer): def run(self): while not self.finished.wait(self.interval): self.function(*self.args,**self.kwargs) print(' ') ##We are now creating a thread timer and controling it timer = RepeatTimer(1,display,['Repeating']) timer.start() #recalling run print('Threading started') time.sleep(10)#It gets suspended for the given number of seconds print('Threading finishing') timer.cancel()
Working with Python Decorator
While working with a Python decorator, will know how to extend the Python Timer for it to be reused. The importance of using decorators is that it gets implemented once, and the function gets timed every time.
- To begin, we will have the Python Timer called before the decorated function, and after the call ends, terminate the Python Timer.
import functools import time def timer(meth): @functools.wraps(meth) def timer_container(*args, **kwargs): click = time.flow() value: object = meth(*args, **kwargs) clock = time.flow() time_passed = click - clock ##getting the time spent print(f"TIME PASSED IS: time_passed:0.2f> SECS") ##displaying time passed to 2 decimal places return value return timer_container()
When the code is run the output should be:
Importance of using Threads
- Threads can be operated concurrently, multithreaded programs can run quicker on computer systems with several CPUs.
- A program can continue to respond to input. This is true on a single CPU as well as several CPUs.
- Threads in a process can share global variable memory. When a global variable is modified in one thread, it affects all threads. Local variables can also exist in a thread.
- Handling of threads in an operating system is easier than handling processes. As a result, they’re sometimes referred to as lightweight processes.
- It can be interrupted hence allowing for high priority processes.
- It can temporarily be put on hold (at times referred to as in sleeping mode) while other threads are running - this is called yielding.
Conclusion
In this article we have learned the following:
- Python Timer Functions: How to use functions such as cancel() to stop execution even before it starts.
- Creating and Using Timer Class: The Timer class is a subclass of class Thread
- Working with Python Decorator: The decorator is used once but the function gets timed on and on.
Enjoy timing your threads.
Peer Review Contributions by: Odhiambo Paul