Skip to content

Commit c63dce0

Browse files
committed
refactor: update fetch_status_task to improve logging and adjust timing comments
1 parent 38428fd commit c63dce0

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

examples/background_task.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import random
23
from datetime import time, timezone
34

45
import discord
@@ -37,35 +38,31 @@ async def time_task(self):
3738
async def before_my_task(self):
3839
await self.wait_until_ready() # Wait until the bot logs in
3940

40-
# Schedule every 10s; each run takes ~15s. With overlap=2, at most 2 runs
41+
# Schedule every 10s; each run takes between 5 to 20s. With overlap=2, at most 2 runs
4142
# execute concurrently so we don't build an ever-growing backlog.
4243
@tasks.loop(seconds=10, overlap=2)
4344
async def fetch_status_task(self):
4445
"""
4546
Practical overlap use-case:
4647
4748
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+
between 5 to 20s due to network latency or rate limits, but we want fresh data
4950
every 10s. Allowing a small amount of overlap avoids drifting schedules
5051
without opening the floodgates to unlimited concurrency.
5152
"""
52-
# Book-keeping so we can show concurrency in logs/messages
53-
run_no = self.fetch_status_task.current_loop
53+
print(f"[status] start run #{self.fetch_status_task.current_loop}")
5454

55-
try:
56-
print(f"[status] start run #{run_no}")
55+
# Simulate slow I/O (e.g., HTTP requests, DB queries, file I/O)
56+
await asyncio.sleep(random.randint(5, 20))
5757

58-
# Simulate slow I/O (e.g., HTTP requests, DB queries, file I/O)
59-
await asyncio.sleep(15)
58+
channel = self.get_channel(1234567) # Replace with your channel ID
59+
msg = f"[status] run #{self.fetch_status_task.current_loop} complete"
60+
if channel:
61+
await channel.send(msg)
62+
else:
63+
print(msg)
6064

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}")
65+
print(f"[status] end run #{self.fetch_status_task.current_loop}")
6966

7067

7168
client = MyClient()

0 commit comments

Comments
 (0)