At the end of foo(), create a Timer which calls foo() itself after 10 seconds.
Because, Timer create a new thread to call foo().
You can do other stuff without being blocked.

import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()

#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011
Answer from kev on Stack Overflow
Top answer
1 of 8
228

At the end of foo(), create a Timer which calls foo() itself after 10 seconds.
Because, Timer create a new thread to call foo().
You can do other stuff without being blocked.

import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()

#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011
2 of 8
129

Simply sleeping for 10 seconds or using threading.Timer(10,foo) will result in start time drift. (You may not care about this, or it may be a significant source of problems depending on your exact situation.) There can be two causes for this - inaccuracies in the wake up time of your thread or execution time for your function.

You can see some results at the end of this post, but first an example of how to fix it. You need to track when your function should next be called as opposed to when it actually got called and account for the difference.

Here's a version that drifts slightly:

import datetime, threading

def foo():
    print datetime.datetime.now()
    threading.Timer(1, foo).start()

foo()

Its output looks like this:

2013-08-12 13:05:36.483580
2013-08-12 13:05:37.484931
2013-08-12 13:05:38.485505
2013-08-12 13:05:39.486945
2013-08-12 13:05:40.488386
2013-08-12 13:05:41.489819
2013-08-12 13:05:42.491202
2013-08-12 13:05:43.492486
2013-08-12 13:05:44.493865
2013-08-12 13:05:45.494987
2013-08-12 13:05:46.496479
2013-08-12 13:05:47.497824
2013-08-12 13:05:48.499286
2013-08-12 13:05:49.500232

You can see that the sub-second count is constantly increasing and thus, the start time is "drifting".

This is code that correctly accounts for drift:

import datetime, threading, time

next_call = time.time()

def foo():
  global next_call
  print datetime.datetime.now()
  next_call = next_call+1
  threading.Timer( next_call - time.time(), foo ).start()

foo()

Its output looks like this:

2013-08-12 13:21:45.292565
2013-08-12 13:21:47.293000
2013-08-12 13:21:48.293939
2013-08-12 13:21:49.293327
2013-08-12 13:21:50.293883
2013-08-12 13:21:51.293070
2013-08-12 13:21:52.293393

Here you can see that there is no longer any increase in the sub-second times.

If your events are occurring really frequently you may want to run the timer in a single thread, rather than starting a new thread for each event. While accounting for drift this would look like:

import datetime, threading, time

def foo():
    next_call = time.time()
    while True:
        print datetime.datetime.now()
        next_call = next_call+1;
        time.sleep(next_call - time.time())

timerThread = threading.Thread(target=foo)
timerThread.start()

However your application will not exit normally, you'll need to kill the timer thread. If you want to exit normally when your application is done, without manually killing the thread, you should use

timerThread = threading.Thread(target=foo)
timerThread.daemon = True
timerThread.start()
🌐
Reddit
reddit.com › r/learnpython › timer with a callback?
r/learnpython on Reddit: Timer with a Callback?
December 8, 2023 -

I swear I have done this in C#, but I cannot remember the names of any of the methods.

The gist of it is that you have a snippet like the following:

def function_to_call_later(metric_name: str) -> None:
    result = metric_service.measure(metric_name)
    print(f"The result is {result}")
    if result > 10:
        do_more_stuff()

Now I want to call function_to_call_later roughly 5 seconds from now without waiting in this thread. The gist of it is like

def main():
    do_stuff()
    timer = Timer(function_to_call_later, ("NameOfMetric",))
    timer.call(5_000) # Call this function in 5,000 MS
    print("App starting')

The output would be;

App starting
... other stuff
The Result is 1000

What is this callback thing I 'm thinking of?

🌐
PyPI
pypi.org › project › timer-event
timer-event · PyPI
March 20, 2023 - The TimerEvent class creates a timed event that triggers at a specified interval. The class uses a Timer object to initiate the timed event. The TimerEvent class can be subscribed to using the subscribe method, which takes a name and a callback function as arguments...
      » pip install timer-event
    
Published   Mar 21, 2023
Version   0.9.1
🌐
MicroPython
docs.micropython.org › en › latest › library › pyb.Timer.html
class Timer – control internal timers — MicroPython latest documentation
The rate at which it counts is the peripheral clock frequency (in Hz) divided by the timer prescaler. When the counter reaches the timer period it triggers an event, and the counter resets back to zero. By using the callback method, the timer event can call a Python function.
🌐
Python Pool
pythonpool.com › home › blog › understanding the python timer class with examples
Understanding the Python Timer Class with Examples - Python Pool
May 23, 2021 - If we want to delay the execution of a function by a certain amount of time, we can use the python timer class. start() and cancel() are two of its methods.
🌐
Runestone Academy
runestone.academy › ns › books › published › thinkcspy › GUIandEventDrivenProgramming › 10_timer_events.html
15.30. Timer Events — How to Think like a Computer Scientist: Interactive Edition
You must specify the correct number of arguments for the callback function when you create the timer event. def task1(): # Do some processing def task2(alpha): # Do some processing def task3(beta, gamma): # Do some processing my_button = tk.Button(application_window, text="Example") my_button.after(1000, task1) my_button.after(2000, task2, 3) # 3 gets passed to the parameter alpha my_button.after(5000, task3, a, b) # a gets passed to the parameter beta # b gets passed to the parameter gamma
🌐
TestDriven.io
testdriven.io › tips › c6f0032c-b533-4b1b-9d62-883ec7bc514b
Tips and Tricks - Call a function after some interval in Python with Timer | TestDriven.io
from threading import Timer def truth(): print("Python rocks!") t = Timer(15, truth) t.start() # truth will be called after a 15 second interval
Find elsewhere
🌐
MicroPython
docs.micropython.org › en › latest › wipy › tutorial › timer.html
5. Hardware timers — MicroPython latest documentation
By using the callback method, the timer event can call a Python function. Example usage to toggle an LED at a fixed frequency: from machine import Timer from machine import Pin led = Pin('GP16', mode=Pin.OUT) # enable GP16 as output to drive the LED tim = Timer(3) # create a timer object using ...
🌐
Delft Stack
delftstack.com › home › howto › python › threading.timer python
Timer Class in the Threading Module in Python | Delft Stack
October 10, 2023 - As we can see, the MyInfiniteTimer class uses the Timer class. It accepts two arguments: t and hFunction, which refer to the number of seconds and the call back function for the Timer object. When a MyInfiniteTimer class object is created, the class’s constructor creates a new timer object but does not start it.
🌐
HotExamples
python.hotexamples.com › examples › pyb › Timer › callback › python-timer-callback-method-examples.html
Python Timer.callback Examples, pyb.Timer.callback Python Examples - HotExamples
def main(): # Configure timer2 as a microsecond counter. tim = Timer(config["timer"], prescaler=(machine.freq()[0] // 1000000) - 1, period=config["timer-period"]) tim2 = Timer(config["led-timer"], freq=config["led-freq"]) tim2.callback(lambda t: pyb.LED(config["led-id"]).toggle()) # Configure channel for timer IC. ch = tim.channel(1, Timer.IC, pin=config["pin-capture"], polarity=Timer.FALLING) # Slave mode disabled in order to configure mem32[config["timer-addr"] + TIM_SMCR] = 0 # Reset on rising edge (or falling in case of inverted detection). Ref: 25.4.3 of STM32F76xxx_reference_manual.pdf mem32[config["timer-addr"] + TIM_SMCR] = (mem32[config["timer-addr"] + TIM_SMCR] & 0xfffe0000) | 0x54 # Capture sensitive to rising edge.
🌐
PyPI
pypi.org › project › timesched
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Real Python
realpython.com › python-timer
Python Timer Functions: Three Ways to Monitor Your Code – Real Python
December 8, 2024 - For more background on classes and object-oriented programming, check out Python Classes: The Power of Object-Oriented Programming, Object-Oriented Programming (OOP) in Python or the official documentation. Classes are good for tracking state. In a Timer class, you want to keep track of when a timer starts and how much time has passed since then. For the first implementation of Timer, you’ll add a ._start_time attribute, as well as .start() and .stop() methods. Add the following code to a file named timer.py: ... 1import time 2 3class TimerError(Exception): 4 """A custom exception used to report errors in use of Timer class""" 5 6class Timer: 7 def __init__(self): 8 self._start_time = None 9 10 def start(self): 11 """Start a new timer""" 12 if self._start_time is not None: 13 raise TimerError(f"Timer is running.
🌐
Pythontutorials
pythontutorials.net › blog › micropython-timer-callback
Mastering MicroPython Timer Callbacks | PythonTutorials.net
July 10, 2025 - We first define a callback function timer_callback that simply prints a message when called. Then we create a timer instance using machine.Timer(0), where 0 is the timer ID.
🌐
Webscale
section.io › home › blog
How to Perform Threading Timer in Python
June 24, 2025 - Get the latest insights on AI, personalization, infrastructure, and digital commerce from the Webscale team and partners.
🌐
GitHub
gist.github.com › cypreess › 5481681
Python periodic thread using timer. You can cancel this thread any time. Thread will live at maximum to the end of one single processing run, otherwise it will end in the same time (especially during a wait time for next run). This code avoids the problem of waiting very long for thread exiting, because it does not uses time.sleep(). Please be aware that this is naive implementation of periodic thread, it does not guarantee runing it __every__ `period` second, it will just wait before following runs at leas
Python periodic thread using timer. You can cancel this thread any time. Thread will live at maximum to the end of one single processing run, otherwise it will end in the same time (especially during a wait time for next run). This code avoids the problem of waiting very long for thread exiting, because it does not uses time.sleep(). Please be aware that this is naive implementation of periodic thread, it does not guarantee runing it __every__ `period` second, it will just wait before following runs at least `period` seconds.
🌐
Blogger
codesgarage.blogspot.com › 2017 › 06 › python-timer-callback-using-threading.html
Think Simple Do Different...: Python Timer Callback using threading
June 30, 2017 - import threading import time def timerCallBack(iTimeSec,isRepeated): print("timerCallBack!") if isRepeated == True : thread
🌐
GeeksforGeeks
geeksforgeeks.org › timer-objects-python
Timer Objects in Python - GeeksforGeeks
June 28, 2017 - # Program to cancel the timer import threading def gfg(): print("GeeksforGeeks\n") timer = threading.Timer(5.0, gfg) timer.start() print("Cancelling timer\n") timer.cancel() print("Exit\n") Output: ... In this article, we will discuss the time module and various functions provided by this module with the help of good examples. As the name suggests Python time module allows to work with time in Python.
🌐
Sipeed
wiki.sipeed.com › soft › maixpy › en › api_reference › machine › timer.html
machine.Timer - Sipeed Wiki
callback: Timer callback function, defines two parameters, one is the timer object Timer, the second is the parameter arg that you want to pass in the definition object, please see the explanation of arg parameters for more