zaro

How to Run a Function Periodically in Python?

Published in Python Scheduling 3 mins read

You can run a function periodically in Python using the time and threading modules, or the sched module for more advanced scheduling. Here's a breakdown of the most common method:

Using time.sleep() and threading.Timer()

This approach is simple and suitable for many use cases.

  1. Define the function you want to run periodically. This is the core logic that will be executed repeatedly.

    def my_periodic_function():
        """This function will be executed periodically."""
        print("Running my_periodic_function...")
        # Add your desired logic here
  2. Use threading.Timer() to schedule the function's execution and repeat it. threading.Timer creates a thread that will execute the function after a specified delay. By rescheduling the timer within the function itself, you can achieve periodic execution.

    import threading
    import time
    
    def run_periodically(interval, function, *args):
        """
        Runs a function periodically using threading.Timer.
    
        Args:
            interval: The time interval in seconds between executions.
            function: The function to be executed.
            *args: Arguments to be passed to the function.
        """
        def wrapper():
            function(*args)
            threading.Timer(interval, wrapper).start()
        threading.Timer(interval, wrapper).start()
    
    # Example usage: Run my_periodic_function every 5 seconds
    run_periodically(5, my_periodic_function)
    
    # Keep the main thread alive to keep the timers running.
    # Otherwise, the program will exit immediately.
    try:
        while True:
            time.sleep(1)  # Check every second to keep the program alive.
    except KeyboardInterrupt:
        print("Program interrupted.  Exiting...")

    Explanation:

    • run_periodically(interval, function, *args) sets up the periodic execution.
    • threading.Timer(interval, wrapper).start() creates a timer that calls the wrapper function after the specified interval.
    • The wrapper function calls your function with the provided *args and then reschedules itself using another threading.Timer. This creates the repeating behavior.
    • The try...except block with time.sleep(1) is crucial. The main thread needs to stay alive for the timer threads to continue running. Without it, the program would exit immediately after starting the first timer. The KeyboardInterrupt allows you to stop the program gracefully (e.g., by pressing Ctrl+C).

Alternative: Using sched module

The sched module provides a more general-purpose event scheduler. It can be useful if you need more complex scheduling requirements.

import sched
import time

def my_scheduled_function():
    print(f"Running my_scheduled_function at {time.time()}")

def run_with_sched(interval, function):
  """Runs a function periodically using the sched module."""
  s = sched.scheduler(time.time, time.sleep)

  def periodic_task(scheduler):
      function()
      scheduler.enter(interval, 1, periodic_task, (scheduler,))

  periodic_task(s)  # Start the first event
  s.run() # blocks until there are no scheduled events left

run_with_sched(2, my_scheduled_function)

Important Considerations:

  • Accuracy: time.sleep() is not perfectly accurate. The actual execution time of your function may vary slightly due to system load and other factors. If precise timing is critical, consider using a real-time operating system or a more specialized library.
  • Non-Blocking: The threading approach allows the main thread to continue executing other tasks while the function runs periodically in the background.
  • Resource Management: Be mindful of the resources used by your periodic function. If it consumes a lot of CPU or memory, it could impact the performance of your application.
  • Error Handling: Consider adding error handling to your periodic function to prevent it from crashing and interrupting the scheduled execution.