The sched module in Python provides a way to schedule tasks to run at specific times. It is an event-driven scheduling library, where tasks can be scheduled to run after a certain delay, or at a certain time, and the scheduler will manage the timing for task execution.
Here are 10 Python code snippets demonstrating how to schedule tasks using the sched module:
1. Basic Task Scheduling
Scheduling a simple task to run after a delay.
Copy
import sched
import time
# Create a scheduler instance
scheduler = sched.scheduler(time.time, time.sleep)
# Define a simple task
def my_task():
print("Task executed!")
# Schedule the task to run after 2 seconds
scheduler.enter(2, 1, my_task)
# Run the scheduler
scheduler.run()
Output:
Copy
Explanation:
enter(delay, priority, action) schedules my_task() to run after 2 seconds.
scheduler.run() processes the scheduled events.
2. Scheduling Multiple Tasks
Scheduling multiple tasks at different times.
Copy
Output:
Copy
Explanation:
Two tasks are scheduled to run at 1 second and 3 seconds respectively.
3. Scheduling Tasks Repeatedly
Scheduling a task to repeat at fixed intervals.
Copy
Output:
Copy
Explanation:
The task repeats every 3 seconds by re-scheduling itself each time it runs.
4. Canceling a Scheduled Task
Canceling a task before it runs.
Copy
Output:
Copy
Explanation:
The task is scheduled, but canceled before it has a chance to run.
5. Task Scheduling with Priority
Scheduling tasks with different priorities.
Copy
Output:
Copy
Explanation:
Tasks with lower priority values run first. In this case, the high priority task runs before the low priority task.
6. Task Scheduling with Absolute Time
Scheduling a task to run at an absolute time.
Copy
Output:
Copy
Explanation:
enterabs(time, priority, action) schedules the task to run at an exact time (absolute time).
7. Multiple Scheduled Tasks with Different Delays
Scheduling multiple tasks with different delays and priorities.
Copy
Output:
Copy
Explanation:
Two tasks are scheduled to run after 1 and 2 seconds respectively.
8. Handling Task Arguments
Passing arguments to the scheduled tasks.
Copy
Output:
Copy
Explanation:
Arguments can be passed to tasks using the argument parameter in enter().
9. Using Delay Time Dynamically
Scheduling tasks with dynamically calculated delay times.
Copy
Output:
Copy
Explanation:
The delay time is calculated dynamically and passed to the enter() method.
10. Scheduling Tasks from a List
Scheduling tasks from a list of functions and delays.
Copy
Output:
Copy
Explanation:
A list of tasks is used to schedule them at different times.
Conclusion:
The sched module is a powerful tool for scheduling tasks and events in Python, particularly useful in event-driven applications. These examples demonstrate how to schedule single or recurring tasks, manage priorities, and pass arguments to tasks.
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def task_to_cancel():
print("This task will not be executed.")
# Schedule the task
event = scheduler.enter(5, 1, task_to_cancel)
# Cancel the task before it runs
scheduler.cancel(event)
# Run the scheduler
scheduler.run()
(no output)
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def task_high_priority():
print("High priority task executed!")
def task_low_priority():
print("Low priority task executed!")
# Schedule tasks with different priorities
scheduler.enter(2, 2, task_low_priority) # Lower priority
scheduler.enter(1, 1, task_high_priority) # Higher priority
# Run the scheduler
scheduler.run()
High priority task executed!
Low priority task executed!
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def task_at_specific_time():
print("Task executed at the specific time!")
# Schedule the task to run at an absolute time (current time + 5 seconds)
run_time = time.time() + 5
scheduler.enterabs(run_time, 1, task_at_specific_time)
# Run the scheduler
scheduler.run()
Task executed at the specific time!
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def task_1():
print("Task 1 executed.")
def task_2():
print("Task 2 executed.")
# Schedule tasks with different delays and priorities
scheduler.enter(1, 1, task_1) # Execute after 1 second
scheduler.enter(2, 2, task_2) # Execute after 2 seconds
# Run the scheduler
scheduler.run()
Task 1 executed.
Task 2 executed.
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def task_with_args(arg1, arg2):
print(f"Task executed with arguments: {arg1}, {arg2}")
# Schedule the task with arguments
scheduler.enter(2, 1, task_with_args, argument=("Hello", "World"))
# Run the scheduler
scheduler.run()
Task executed with arguments: Hello, World
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def task_dynamic_delay():
print("Task executed with dynamic delay.")
# Schedule the task after a dynamically calculated delay
delay_time = 5 * 2 # 10 seconds delay
scheduler.enter(delay_time, 1, task_dynamic_delay)
# Run the scheduler
scheduler.run()
Task executed with dynamic delay.
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def task1():
print("Task 1 executed.")
def task2():
print("Task 2 executed.")
tasks = [
(1, task1),
(2, task2),
]
# Loop through the task list and schedule each one
for delay, task in tasks:
scheduler.enter(delay, 1, task)
# Run the scheduler
scheduler.run()