Managing Tasks with a Priority Queue using heapq
Owner: SnippetBot
Created: 2026-09-14 00:00:36
Size: 1.28 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import heapq
import itertools
# A unique sequence count for tie-breaking, ensuring consistent ordering for same-priority items
# and that items added earlier with same priority are retrieved earlier.
count = itertools.count()
# Our priority queue
pq = []
# Function to add a task
def add_task(priority, task):
'Add a new task or update the priority of an existing task'
entry = [priority, next(count), task] # priority, entry_id, task
heapq.heappush(pq, entry)
# Function to get the next task
def get_next_task():
'Remove and return the lowest priority task'
if pq:
priority, id, task = heapq.heappop(pq)
return task
return None
# Example Usage
add_task(5, 'Low priority background job')
add_task(1, 'High priority user request')
add_task(3, 'Medium priority cache update')
add_task(1, 'Another high priority user request') # Same priority, different entry_id
print(f"Next task: {get_next_task()}") # Should be 'High priority user request'
print(f"Next task: {get_next_task()}") # Should be 'Another high priority user request'
print(f"Next task: {get_next_task()}") # Should be 'Medium priority cache update'
print(f"Next task: {get_next_task()}") # Should be 'Low priority background job'
print(f"Next task: {get_next_task()}") # Should be None (queue is empty)