GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python sched Module - Event Scheduling Python sched Modulelast modified March 10, 2025
The
Unlike threading or multiprocessing, Basic UsageThis example shows how to schedule a task with a delay. basic_scheduler.py
import sched
import time
def print_message():
print("Hello, World!")
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(5, 1, print_message) # Run after 5 seconds
scheduler.run() # Start the scheduler
Here, Repeating EventsThis example creates a task that repeats every 5 seconds. repeating_events.py
import sched
import time
def print_message():
print(f"Tick at {time.ctime()}")
scheduler.enter(5, 1, print_message) # Reschedule
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(5, 1, print_message) # First run
scheduler.run() # Runs indefinitely
The function reschedules itself, forming a loop. Note that
Priority and ArgumentsThis example uses priorities and passes arguments to tasks. priority_arguments.py
import sched
import time
def print_message(msg):
print(msg)
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(5, 2, print_message, ("Low priority",)) # Priority 2
scheduler.enter(5, 1, print_message, ("High priority",)) # Priority 1
scheduler.run()
Lower priority numbers run first if times overlap. The
Cancel Scheduled EventsThis example cancels a scheduled task before it runs. cancel_event.py
import sched
import time
def print_message():
print("This won't run!")
scheduler = sched.scheduler(time.time, time.sleep)
event = scheduler.enter(5, 1, print_message)
scheduler.cancel(event) # Remove from queue
scheduler.run() # Nothing happens
Advanced: Using Absolute TimeThis example schedules a task at an exact time. absolute_time.py
import sched
import time
def print_message():
print(f"Event at {time.ctime()}")
scheduler = sched.scheduler(time.time, time.sleep)
run_time = time.time() + 5 # 5 seconds ahead
scheduler.enterabs(run_time, 1, print_message)
scheduler.run()
New Example: Task with Exception HandlingThis example safely handles errors in scheduled tasks. exception_handling.py
import sched
import time
def risky_task():
try:
result = 10 / 0 # Simulate error
except ZeroDivisionError:
print("Caught an error!")
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(3, 1, risky_task) # Run after 3 seconds
scheduler.run()
Wrapping tasks in New Example: Scheduled File CleanupThis example schedules a file deletion task. file_cleanup.py
import sched
import time
import os
def cleanup_temp_file():
file = "temp.txt"
if os.path.exists(file):
os.remove(file)
print(f"Deleted {file}")
else:
print(f"{file} not found")
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(5, 1, cleanup_temp_file)
scheduler.run()
This simulates a cleanup job, useful for temp files or logs. Check file existence to avoid errors. Best Practices for sched
SourcePython sched Module Documentation
This tutorial explored the AuthorMy name is Jan Bodnar, a passionate programmer with years of experience. Since 2007, I've written over 1400 articles and 8 e-books, with over eight years teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |