The best way is to start the timer thread once. Inside your timer thread you'd code the following

class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("my thread")
            # call a function

In the code that started the timer, you can then set the stopped event to stop the timer.

stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()
Answer from Hans Then on Stack Overflow
🌐
Real Python
realpython.com › python-timer
Python Timer Functions: Three Ways to Monitor Your Code – Real Python
December 8, 2024 - Using a timer involves recording timestamps before and after a specific code block and calculating the time difference to determine how long your code took to run. [ ... ] ## Read the full article at https://realpython.com/python-timer/ » * * *
Discussions

How to make a timer ?
sounds like you can use the time, module for this or schedule module along with time coukd work as well. Im still a beginner too. https://www.geeksforgeeks.org/python-time-module/ More on reddit.com
🌐 r/learnpython
3
3
August 14, 2024
time - how do I make a Timer in Python - Stack Overflow
How do you create a timer in python? My project is a speed typing test and the timer is there to time the length it takes the user to type. The first task the user types is the alphabet, as fast as... More on stackoverflow.com
🌐 stackoverflow.com
python - Run certain code every n seconds - Stack Overflow
Is there a way to, for example, print Hello World! every n seconds? For example, the program would go through whatever code I had, then once it had been 5 seconds (with time.sleep()) it would execute More on stackoverflow.com
🌐 stackoverflow.com
Time.time() use as a timer
11.6 seconds to list 8 files seems too long? #! /usr/bin/python3.6 # # Time how long a section takes to execute # /home/andy/Downloads has 8 files Time to list files in directory: 11.606783628463745 import math import os import time our_list = list(range(10000000)) element = 7000000 start = ... More on discuss.python.org
🌐 discuss.python.org
7
0
October 8, 2022
🌐
PyPI
pypi.org › project › multitimer
multitimer · PyPI
A pure-python auto-repeating timer that can be stopped and restarted multiple times.
      » pip install multitimer
    
Published   Nov 27, 2020
Version   0.3
🌐
LearnDataSci
learndatasci.com › solutions › python-timer
Create a Timer in Python: Elapsed Time, Decorators, and more – LearnDataSci
One advantage of using the @contextmanager decorator to define our timer is that we can use the timer both using the with statement and as a function decorator, like in the last example. If we wanted to time a certain operation once, we could call in timer() using a with statement.
🌐
Medium
k3no.medium.com › taming-time-in-python-65a625ade93f
Taming Time in Python. Timers, stopwatches, threading and… | by Keno Leon | Medium
November 10, 2021 - The result from running the previous script should be:Hello from : TIMER THREE Hello from : TIMER ONE Hello from : TIMER TWOA timer is made by defining the interval in seconds to wait before running the function/callback, the only weird thing ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-create-a-countdown-timer-using-python
How To Create a Countdown Timer Using Python? - GeeksforGeeks
May 9, 2025 - import time def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end='\r') # Overwrite the line each second time.sleep(1) t -= 1 print("Fire in the hole!!") t = input("Enter the time in seconds: ") countdown(int(t))
🌐
GitHub
github.com › takhyun12 › python-repeated-timer
GitHub - takhyun12/python-repeated-timer: Easy-to-use and high-performance timer · GitHub
This code is GUI freezing issue won't be happening, and performance of the timer won't be affected by any event. Python Repeated Timer is a open-source library based on Thread Timer, and this asynchronously triggers the event every N seconds.
Author   takhyun12
🌐
Reddit
reddit.com › r/learnpython › how to make a timer ?
r/learnpython on Reddit: How to make a timer ?
August 14, 2024 -

Hello guys ! I’m starting with python a week ago, I don’t have all the knowledge etc…, but I’m very curious and I wish to know a method or how to make a Timer in python… like my timer start at 35min and decrease to 0 or to 0 to 35. If anybody have an idea how to do this, I'll take it !! See you ! 🐍

Find elsewhere
🌐
PyPI
pypi.org › project › interval-timer
interval-timer · PyPI
November 28, 2022 - interval-timer is a Python package that enables iterating over a sequence of regular time intervals with high precision.
      » pip install interval-timer
    
Published   Nov 28, 2022
Version   1.0.0
🌐
Python Assets
pythonassets.com › posts › executing-code-every-certain-time
Executing Code Every Certain Time | Python Assets
March 13, 2022 - How to a run a Python function in the background at regular intervals (also known as timer) using the «threading» standard module.
🌐
The Coding Process
thecodingprocess.hashnode.dev › creating-a-countdown-timer-using-python
Creating a Countdown Timer Using Python
June 10, 2022 - T > Enter a time User > 5s T > 5 seconds left > 4 seconds left > 3 seconds left > 2 seconds left > 1 second left Continuous indefinite beeping Hint: A "beeping sound" can be achieved using the "bell character", or any library of your choice. This is the full code. It would be explained in bits throughout this article. import time # For sleep import datetime # For timedelta # import winsound # For Beep on Windows OS # Countdown timer function def countdown(hrs, mins, sec): """Counts down time and gives off beeps when the time inputted elapse""" # Calculate the total number of seconds total_seco
🌐
Udacity
udacity.com › blog › 2021 › 09 › create-a-timer-in-python-step-by-step-guide.html
Create a Timer in Python: Step-by-Step Guide | Udacity
September 27, 2022 - Within the loop, we use the timedelta() ... on the timer. The program prints the time left in hours:minutes:seconds format for the user to see. Immediately after, the program pauses for one second, reduces total_seconds by one second, and repeats the while loop. The loop continues until total_seconds reaches zero, at which point the program leaves the while loop and prints “Bzzzt! The countdown is at zero seconds!” · You can use Python to measure ...
🌐
Python
docs.python.org › 2.4 › lib › timer-objects.html
7.5.7 Timer Objects
November 18, 2006 - This class represents an action that should be run only after a certain amount of time has passed -- a timer.
🌐
GitHub
gist.github.com › TomFaulkner › 6a790051701c291f53c07de9192c7fb6
Python Perpetual (Repeating) Timer · GitHub
September 7, 2019 - def handle_function(self): self.hFunction() self.thread = Timer(self.t,self.handle_function) self.thread.start() def start(self): self.thread.start() def cancel(self): self.thread.cancel() def apagar(): print ('ipsem lorem') def encender(): s.calcel() t.calcel() t = perpetualTimer(0.05, apagar) s = perpetualTimer(5, encender) t.start() s.start() generate this error · Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 1073, in run self.function(*self.args, **self.kwargs) File "hilo_infinito_fallo.py", line 15, in handle_function self.hFunction() File "hilo_infinito_fallo.py", line 29, in encender s.calcel() AttributeError: perpetualTimer instance has no attribute 'calcel' can you help me?
Top answer
1 of 7
444
import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

2 of 7
159

My humble take on the subject, a generalization of Alex Martelli's answer, with start() and stop() control:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()
    
    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)
    
    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True
    
    def stop(self):
        self._timer.cancel()
        self.is_running = False

Usage:

from time import sleep

def hello(name):
    print "Hello %s!" % name

print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
    sleep(5) # your long-running job goes here...
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

Features:

  • Standard library only, no external dependencies
  • start() and stop() are safe to call multiple times even if the timer has already started/stopped
  • function to be called can have positional and named arguments
  • You can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!