Priority Queue Orders Scheduled Jobs
Order scheduled jobs with queue.PriorityQueue and a sequence tiebreaker, so urgent work always dequeues first and equal priorities stay stable.
Code
import itertools
from queue import PriorityQueue
queue = PriorityQueue()
tiebreaker = itertools.count()
# 相同优先级由自增序号决定先后,避免程序去比较 job 名字
jobs = [(5, 'cleanup'), (1, 'alert'), (3, 'report'), (1, 'page')]
for priority, name in jobs:
queue.put((priority, next(tiebreaker), name))
print('queued:', queue.qsize(), 'jobs')
while not queue.empty():
priority, seq, name = queue.get()
print(f'priority={priority} seq={seq} job={name}')Output
Captured from a sandboxed run of this snippet in the build pipeline.
queued: 4 jobs
priority=1 seq=1 job=alert
priority=1 seq=3 job=page
priority=3 seq=2 job=report
priority=5 seq=0 job=cleanupHow the snippet works
Iteration happens inside for priority, name in jobs — everything outside it runs once. PriorityQueue are the only symbols borrowed from queue — the coupling is explicit and narrow.
Module-level bindings hold the data — queue, tiebreaker, jobs — with no function scope in between.
Watch out for
- Requires
queueas a package; the snippet will not run without it.
Applying it
The demo output is labeled (queued:, priority=), so every printed line maps back to its originating operation.
Interactive Tools for This Topic
Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `queue`, `tiebreaker`, `jobs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.