Run certain code every n seconds
Execute code at intervals in Python by using threading.Timer. It schedules and repeats a function's execution every n seconds:
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:
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:
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
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
Was this article helpful?