1
+ import asyncio
1
2
from datetime import time , timezone
2
3
3
4
import discord
@@ -10,7 +11,6 @@ def __init__(self, *args, **kwargs):
10
11
11
12
# An attribute we can access from our task
12
13
self .counter = 0
13
-
14
14
# Start the tasks to run in the background
15
15
self .my_background_task .start ()
16
16
self .time_task .start ()
@@ -37,6 +37,36 @@ async def time_task(self):
37
37
async def before_my_task (self ):
38
38
await self .wait_until_ready () # Wait until the bot logs in
39
39
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
+
40
70
41
71
client = MyClient ()
42
72
client .run ("TOKEN" )
0 commit comments