Build a basic task scheduler that selects the highest-priority pending job.
What You Will Learn
heapq can order tasks by priority and an arrival counter. Use tuples (priority, sequence, task_name), so duplicate priorities do not require comparing task payloads. This example models dispatching, not real-time execution.
Updating a queued task priority usually requires adding a new entry and invalidating the old one.
Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
import heapq
from itertools import count
pending = []
sequence = count()
def schedule(priority, task_name):
heapq.heappush(pending, (priority, next(sequence), task_name))
schedule(2, 'backup')
schedule(1, 'security-check')
schedule(2, 'report')
while pending:
priority, arrival, task_name = heapq.heappop(pending)
print(task_name)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: heapq, itertools.
- The function schedule defines reusable behavior; its body executes when it is called, not when it is declared.
- The variable pending holds the result of []. Later lines use that value or inspect how it changes.
- The variable sequence holds the result of count(). Later lines use that value or inspect how it changes.
Expected output from the example:
security-check
backup
report
When You Would Use This
This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.
Practice: Modify the Code
Add a cancellation flag and skip cancelled tasks when they are popped.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Using task objects as a tuple tiebreaker even when the objects are not mutually orderable.
- Overlooking this documented constraint: use tuples (priority, sequence, task_name), so duplicate priorities do not require comparing task payloads.
Key Takeaways
- Build a basic task scheduler that selects the highest-priority pending job.
- heapq can order tasks by priority and an arrival counter.
- Updating a queued task priority usually requires adding a new entry and invalidating the old one.