Threading timer stop python
Timer objects are created using Timer class which is a subclass of the Thread class. Using this class we can set a delay on any action that should be run only after a certain amount of time has passed(timer) and can easily be cancelled during that delay. Show Timers are started, just like normal threads, by calling their start() method. A timer thread can be stopped (before its action has begun) by calling its cancel() method. Timer object is generally used to implement scheduled tasks which supposed to be executed only after a certain instant of time. Also, its not necessary that the Timer object will be executed exactly after the scheduled time as after that the python intrepreter looks for a thread to execute the timer object task, which if not available leads to more waiting. Syntax for creating Timer objectFollowing is the syntax for the Timer class constructor: threading.Timer(interval, function, args=[], kwargs={})This way we can create a timer object that will run the function with arguments args and keyword arguments kwargs, after interval seconds have passed. Methods of Timer classIn the Timer class we have two methods used for starting and cancelling the execution of the timer object. start() methodThis method is used to start the execution of the timer object. When we call this method, then the timer object starts its timer. cancel() methodThis method is used to stop the timer and cancel the execution of the timer object's action. This will only work if the timer has not performed its action yet. Time for an ExampleBelow we have a simple example where we create a timer object and start it. import threading def task(): print("timer object task running...") if __name__=='__main__': t = threading.Timer(10, task) t.start() # after 10 seconds, task will be executedThe above program is a simple program, now let's use the cancel method to cancel the timer object task's execution. In the program above, first comment the code on line number 13 and 14 and run the program, then uncomment those lines and see the cancel() method in action. Introduction to Python Threading TimerThe timer is a subsidiary class present in the python library named “threading”, which is generally utilized to run a code after a specified time period. Python’s threading.Timer() starts after the delay specified as an argument within the threading. Timer class itself and thus delaying the execution of the subsequent operation by the same duration of time. threading.Timer() class needs to be started explicitly by utilizing the start() function corresponding to that threading.Timer() object. It can also be stopped even before it has started execution by utilizing the cancel() function corresponding to that threading.Timer() object. Syntax of Python Threading TimerWe need to import the python library “threading” to use the “Timer” function specified in it. import threading as th Here we have specified a short name for the library by creating an alias for the same using the “as” keyword. In Short, Aliasing the Python library gives us the capability of utilizing this shorthand notation to call the Timer() class as: th.Timer() instead of threading.Timer() Timer() classed is specified with multiple arguments, out of which the “Delay Duration / Interval” and the corresponding function that needs to be delayed are quire important ones. T = th.Timer (Delay Duration, function, args = None, kwargs = None)
Here we are creating a timer object named as “T”, which can be stated explicitly by utilizing. T.start() It can also be stopped even before it has started execution by utilizing the cancel() function corresponding to this timer object “T” as: T.cancel() Examples of Python Threading TimerFollowing are the different examples of the python threading timer. Example #1Let’s try to understand its operation with the help of the below Example: Code: ##Program to demonstrate the usage of threading.Timer() class within Python import threading as th ## Creating a function def prnt(): print("EDU CBA \n") T = th.Timer(3.0, prnt) T.start() print("Exit Program\n") Output: Case 1: EDU CBA Case 2: Exit Program Although the “prnt” function is being called even before we are printing the text “Exit Program”, but still results may vary as it’s dependent on multiple factors.
Example #2Let’s now discuss the importance of the cancel function available in Timer class with the help of the below example: Suppose we want to cancel the execution of this time delayed function “prnt” if in case the control reaches the end of the program before that specified delay time (3.0 seconds) itself, once the timer has been started [ T.start() ], then we can place the below statement at the end of the program. T.cancel() Or otherwise, if the program takes more than the specified delay time (i.e. 3 seconds in this case), then the cancel statement will act as a redundant one. The reason being, the Delayed function would already have been executed until the control reached the T.cancel() function itself. Code: Let's try to execute the below program: ##Program to demonstrate the usage cancel() function within Timer class import threading as th ## Creating a function def prnt(): print("EDU CBA \n") T = th.Timer(3.0, prnt) T.start() print("Exit Program\n") T.cancel() Output: Case 1: EDU CBA Case 2: Exit Program Case 3: EDU CBA Case 4: Exit Program If will think about the permutation and combinations of the outputs presented by the above program, then case 3 is not at all feasible. The reason being the below statement is not at all governed by the Timer object. print("Exit Program\n") Case 1 is feasible when the control of the program takes more than the specified delay time (3.0 seconds) itself to reach the below statement, once the timer has been started [ T.start() ] T.cancel() Case 2 is feasible when the control of the program takes more than the specified delay time (3.0 seconds) itself to reach the below statement but executes the print(“Exit Program\n”) before that specified delay time (3.0 seconds) once the timer has been started [ T.start() ] T.cancel() Case 4 is feasible when the control of the program reaches and executes the cancel() function before that specified delay time (3.0 seconds) once the timer has been started [ T.start() ] T.cancel() In this case, the Timer object will be canceled even before it has executed the “prnt” function. Example #3Code: ##Program to demonstrate the if cancel() function cancels the start() function or the Timer object itself import threading as th ## Creating a function def prnt(): print("EDU CBA \n") T = th.Timer(3.0, prnt) T.cancel() T.start() print("Exit Program\n") Output: Case 1: Exit Program Case 2: Exit Program In this example, we have placed T.cancel() even before we have explicitly called the Timer object using the below statement. T.start() The question here is, can a canceled Timer() object “T” be called by using the start() function? What do you think? The answer is No !!! Once the object is canceled. It can not be started. Thus the output will be as per Case 2. Conclusion
Recommended ArticlesThis is a guide to Python Threading Timer. Here we discuss the Introduction to Python Threading Timer along with different examples and code implementation. You may also look at the following articles to learn more – |