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.

PythonResilience

Code

pythonsnippet
16 lines
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=cleanup

How 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 queue as 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

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`.