Learning Python: How to use Timer to develop a clock using Python

Sometime in your application, you want to have the ability to execute some action after certain time. E.g. you may be saying that I want to start calculations after 30 minutes of completion of next step. Or you may have requirement of executing certain action continuously at fixed interval. In programming languages line C#, Java, C, C++ etc. you have class like Timer that provides this type of functionality. Python is not different in that regard. It also has a Timer class.

Following code snippet shows to build a Clock class that ticks at fixed interval. This sample prints current time after every one second. You can replace the code in tick function to do whatever action you want to take.

from datetime import datetime
from threading import Timer

class Clock():
    """ Clock class """
    def __init__(self, frequency=1.0):
        self.frequency = frequency
        self.counter = 0

    def tick(self, frequency=1):
        self.counter = self.counter+1
        now = datetime.today()
        print(f"{self.counter}: {now}")
        self.timer = Timer(frequency, self.tick)

    def stop(self):

myClock = Clock()

This sample code also implements stop function that allows you to stop the execution.

Keep in mind that Python Timer object ticks only one time after you call start function on it. To keep it ticking all the time, I have called start function from with in tick function.




1.3 °C / 34.4 °F

weather conditions Clouds

Monthly Posts

Blog Tags