144. Scheduling Tasks with sched
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.
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:
Explanation:
enter(delay, priority, action)schedulesmy_task()to run after 2 seconds.scheduler.run()processes the scheduled events.
2. Scheduling Multiple Tasks
Scheduling multiple tasks at different times.
Output:
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.
Output:
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.
Output:
Explanation:
The task is scheduled, but canceled before it has a chance to run.
5. Task Scheduling with Priority
Scheduling tasks with different priorities.
Output:
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.
Output:
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.
Output:
Explanation:
Two tasks are scheduled to run after 1 and 2 seconds respectively.
8. Handling Task Arguments
Passing arguments to the scheduled tasks.
Output:
Explanation:
Arguments can be passed to tasks using the
argumentparameter inenter().
9. Using Delay Time Dynamically
Scheduling tasks with dynamically calculated delay times.
Output:
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.
Output:
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.
Last updated