Then we stopped the timer and again waited for 5 seconds. Next, we waited for 5 seconds or let the timer run for 5 seconds. To showcase the working of the MyInfiniteTimer class, we first created a new MyInfiniteTimer class object at line 29 and then called the start() method. Once the current timer ends, the handler or the handle_function() creates a new timer with the same configurations as the previous timer and starts it. And using the stop() method, the timer can be stopped. The timer can be launched using the start() method of the MyInfiniteTimer class. When a MyInfiniteTimer class object is created, the class’s constructor creates a new timer object but does not start it. It accepts two arguments: t and hFunction, which refer to the number of seconds and the call back function for the Timer object. T = MyInfiniteTimer(1, print_current_datetime)Īs we can see, the MyInfiniteTimer class uses the Timer class. Self.thread = Timer(self.t, self.handle_function)
#Python active timer modules code#
Refer to the following code for the same. Now that we are done with the theory, let us understand how we can practically use this class to create an infinite timer. And to stop a running timer, we can use the cancel() method. We have to call the start() method to launch them.
start() method is used to start the timer and cancel() method is used to cancel it. This class has two important functions, namely, start() and cancel(). interval refers to the number of seconds after which the code should be executed, and function is the call back function that should be called when the required time has elapsed. It accepts two arguments, namely, interval and function. The Timer class is a subclass of the Thread class and can be used to execute code after some units of time. Once it starts, it should call the specified function. In this article, we will see how we can use this class and understand it better with the help of an example. threading.Timer () This function of threading module is used to create a new Thread and letting it know that it should only start after a specified time. Now, the threading module has a class Timer, which can be used to perform some action or run some code after x amount of time. In Python, we can implement threading using the threading module. Threading is the technique of running multiple threads concurrently to achieve parallelism. Perform a Parallel Processing in Python.