heapq Fires Deferred Tasks In Deadline Order

Hold deferred callbacks in a min-heap keyed by monotonic deadlines: pop everything due now, then report the next task still waiting.

PythonResilience

Code

pythonsnippet
25 lines
import heapq
from time import monotonic

# (deadline, seq, label):monotonic 时钟 + 单调计数器做平局裁决
now = monotonic()
timers = []
for seq, (delay, label) in enumerate([
    (0.30, 'flush-log'),
    (0.05, 'heartbeat'),
    (0.05, 'probe'),
    (0.12, 'cleanup'),
]):
    heapq.heappush(timers, (now + delay, seq, label))

fired = []
while timers:
    deadline, seq, label = timers[0]
    # 到期的任务全部先出队:同一 deadline 按插入顺序触发
    if deadline <= now + 0.35:
        heapq.heappop(timers)
        fired.append(label)

print('fired    :', fired)
print('remaining:', [label for _, _, label in timers])
print('next due :', timers[0][2] if timers else 'idle')

Output

Captured from a sandboxed run of this snippet in the build pipeline.

fired    : ['heartbeat', 'probe', 'cleanup', 'flush-log']
remaining: []
next due : idle

How the snippet works

Repetition is confined to for seq, (delay, label) in enumerate([ — the rest of the file is straight-line. The snippet’s external surface is monotonic, all of it via heapq.

Module-level bindings hold the data — now, timers, fired — with no function scope in between.

What to watch for

  • heapq must be installed first — the snippet imports it directly.

Applying it

Running the file prints labeled results such as fired :, remaining:, next due : — each operation’s effect is visible in the output.

Statements that matter

if deadline <= now + 0.35:
    heapq.heappop(timers)
    fired.append(label)

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `now`, `timers`, `fired`.