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 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
🌐
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
Python tip: You can use Timer to run some function only after a certain amount of time has passed · An example👇 · from threading import Timer def truth(): print("Python rocks!") t = Timer(15, truth) t.start() # truth will be called after a 15 second interval ·
🌐
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.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › hardware and peripherals › raspberry pi pico › micropython
callback from a timer ? - Raspberry Pi Forums
Timer(period=100, mode=Timer.PERIODIC, callback=acc_decc)Is simply wrong. You appear to be confusing the constructor and init() methods. You never start the timer. That means the callback will never happen. No, that is a valid way of creating and starting a timer in one line, no separate call to init() is required.
🌐
MicroPython
docs.micropython.org › en › latest › library › machine.Timer.html
class Timer – control hardware timers — MicroPython latest documentation
Timer class provides the ability to trigger a Python callback function after an expiry time, or periodically at a regular interval.
🌐
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
Find elsewhere
🌐
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
The method takes at least 2 arguments: the amount of time (in milliseconds) to wait before generating the event, and the callback function to call after the time has elapsed. In the example below, the function a_callback_function will be called one second (1000 milliseconds) after the timer-event ...
🌐
Sipeed
wiki.sipeed.com › soft › maixpy › en › api_reference › machine › timer.html
machine.Timer - Sipeed Wiki
MicroPython's Timer class defines the basic operation of executing a callback within a given time period (or executing a callback after a delay), and allows more non-standard behaviors to be defined on specific hardware (so it cannot be ported to other boards).
🌐
MicroPython
docs.micropython.org › en › v1.9.3 › pyboard › library › pyb.Timer.html
class Timer – control internal timers — MicroPython 1.9.3 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.
🌐
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.
🌐
Python Assets
pythonassets.com › posts › executing-code-every-certain-time
Executing Code Every Certain Time | Python Assets
March 13, 2022 - Following this same principle, we can use the threading.Thread class to move a function into a child thread, where a code execution is repeated every certain time, with the help of the timer.sleep() (docs) standard function.
🌐
Real Python
realpython.com › python-timer
Python Timer Functions: Three Ways to Monitor Your Code – Real Python
December 8, 2024 - In this tutorial, you’ll explore three different approaches to implementing timers: classes, decorators, and context managers. Each method offers unique advantages, and you’ll learn when and how to use them to achieve optimal results. Plus, you’ll have a fully functional Python timer that can be applied to any program to measure execution time efficiently.
🌐
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 run any function after a certain interval of time, we can use the python timer class. In the args parameter, which is None by default, we can specify the arguments we want to give to the callback method.
🌐
Readthedocs
rumps.readthedocs.io › en › latest › Timer.html
Timer — rumps 0.2.0 documentation - Read the Docs
Python abstraction of an Objective-C event timer in a new thread for application. Controls the callback function, interval, and starting/stopping the run loop.
🌐
MicroPython
docs.micropython.org › en › latest › wipy › tutorial › timer.html
5. Hardware timers — MicroPython latest documentation
from machine import Timer from machine import Pin tim = Timer(1, mode=Timer.PERIODIC, width=32) tim_a = tim.channel(Timer.A | Timer.B, freq=1) # 1 Hz frequency requires a 32 bit timer led = Pin('GP16', mode=Pin.OUT) # enable GP16 as output to drive the LED def tick(timer): # we will receive the timer object when being called global led led.toggle() # toggle the LED tim_a.irq(handler=tick, trigger=Timer.TIMEOUT) # create the interrupt
🌐
Enthought
docs.enthought.com › pyface › timer.html
Timers — pyface 8.0.0 documentation
April 6, 2023 - This class is meant to be directly instantiated, providing at a minimum a callable value for the callback trait, along with an optional tuple of args and/or optional dict of kwargs. from pyface.timer.api import CallbackTimer def print_time(): print("The time is {}".format(datetime.datetime.now())) CallbackTimer.timer(callback=print_time, interval=0.5, expire=60)