Explain Codes LogoExplain Codes Logo

Run certain code every n seconds

python
timers
apscheduler
threading
Anton ShumikhinbyAnton Shumikhin·Mar 5, 2025
TLDR

Execute code at intervals in Python by using threading.Timer. It schedules and repeats a function's execution every n seconds:

import threading def run_every_n_seconds(seconds, action, *args): # Like Groundhog Day, but with less Bill Murray threading.Timer(seconds, run_every_n_seconds, [seconds, action] + list(args)).start() # Now, on with the show! action(*args) def example_task(): print("Once upon a time, every 5 seconds...") # 5 seconds is just an example, use your own value run_every_n_seconds(5, example_task)

Alter '5' to your desired interval and substitute example_task with your function to run it strategically without obstructing other codes.

Timely explanation with code variants

Ever see a train racing against time? Neither have I. What we have here though, is code racing against time. Using a timer, your tasks can do the same. Make sure they are fast runners though, to avoid overlapping tasks and welcoming chaos.

Managing time drift

Time drift is like a bad drift in Fast & Furious. It's something you want to avoid. To do this, consider the finish line by calculating the exact expected time of the next call, not just the 'about-a-minute' estimates.

Handling shutdown and cleanup

Like any responsible party animal, your code should clean up after itself, especially on program exit. Make use of try/finally blocks to ensure active timers get the elbow, not lingering around like unwelcome guests:

import threading timer = None # It's lonely being a None def stop_timer(): global timer # Time's up, out you go timer! if timer is not None: timer.cancel() def task(): # Imagine an epic dance-off happening here print("And the winner is...!") try: timer = threading.Timer(5, task) # Ready, set, go! timer.start() finally: stop_timer() # Pack up the party!

Rich scheduling with APScheduler

When built-in timers seem too vanilla, go for the APScheduler. It's the hot fudge, whipped cream, and cherry on top of your scheduling tasks. Whether it's performing intricate cron-style dances, mingling with different job stores, or just a good, old-fashioned interval tasks, APScheduler does it with style and grace. Here's the absolute basic:

from apscheduler.schedulers.background import BackgroundScheduler def periodic_task(): # This task wants to dance--again and again! print("Yet another glorious run!") scheduler = BackgroundScheduler() scheduler.add_job(periodic_task, 'interval', seconds=5) # Dance-off every 5 seconds! scheduler.start() try: # Here we just chill while True: time.sleep(1) except (KeyboardInterrupt, SystemExit): # Whoops, someone called security scheduler.shutdown()

Jamming with execution modes and patterns

Showcasing long tasks

For tasks that love the limelight and take longer on stage, handling them delicately is vital. Let a flag or a semaphore be your stage manager here, skipping or queueing the functions with precision.

Commanded execution with a custom class

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.running = False self.start() def _run(self): self.running = False # First, siesta time... self.start() self.function(*self.args, **self.kwargs) # Then, action! def start(self): if not self.running: # Teeing off! self._timer = threading.Timer(self.interval, self._run) self._timer.start() self.running = True def stop(self): # 'Farewell, cruel world!', said the timer. self._timer.cancel() self.running = False

Wrapping it in a class like RepeatedTimer will make sure your code dances to your beat, not the other way around.

Doing the simple dance with time.sleep

import time def task(): # Here we're busting some moves print("And... cut!") while True: task() # The show must go on! time.sleep(5) # Rest for 5 sec, then back to the grind