Skip to content

Commit 38428fd

Browse files
committed
feat: add fetch_status_task to poll external service with concurrency control
1 parent 4bb3a27 commit 38428fd

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

examples/background_task.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
from datetime import time, timezone
23

34
import discord
@@ -10,7 +11,6 @@ def __init__(self, *args, **kwargs):
1011

1112
# An attribute we can access from our task
1213
self.counter = 0
13-
1414
# Start the tasks to run in the background
1515
self.my_background_task.start()
1616
self.time_task.start()
@@ -37,6 +37,36 @@ async def time_task(self):
3737
async def before_my_task(self):
3838
await self.wait_until_ready() # Wait until the bot logs in
3939

40+
# Schedule every 10s; each run takes ~15s. With overlap=2, at most 2 runs
41+
# execute concurrently so we don't build an ever-growing backlog.
42+
@tasks.loop(seconds=10, overlap=2)
43+
async def fetch_status_task(self):
44+
"""
45+
Practical overlap use-case:
46+
47+
Poll an external service and post a short summary. Each poll may take
48+
~15s due to network latency or rate limits, but we want fresh data
49+
every 10s. Allowing a small amount of overlap avoids drifting schedules
50+
without opening the floodgates to unlimited concurrency.
51+
"""
52+
# Book-keeping so we can show concurrency in logs/messages
53+
run_no = self.fetch_status_task.current_loop
54+
55+
try:
56+
print(f"[status] start run #{run_no}")
57+
58+
# Simulate slow I/O (e.g., HTTP requests, DB queries, file I/O)
59+
await asyncio.sleep(15)
60+
61+
channel = self.get_channel(1234567) # Replace with your channel ID
62+
msg = f"[status] run #{run_no} complete"
63+
if channel:
64+
await channel.send(msg)
65+
else:
66+
print(msg)
67+
finally:
68+
print(f"[status] end run #{run_no}")
69+
4070

4171
client = MyClient()
4272
client.run("TOKEN")

0 commit comments

Comments
 (0)