|
1 | 1 | import asyncio
|
| 2 | +import random |
2 | 3 | from datetime import time, timezone
|
3 | 4 |
|
4 | 5 | import discord
|
@@ -37,35 +38,31 @@ async def time_task(self):
|
37 | 38 | async def before_my_task(self):
|
38 | 39 | await self.wait_until_ready() # Wait until the bot logs in
|
39 | 40 |
|
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 |
41 | 42 | # execute concurrently so we don't build an ever-growing backlog.
|
42 | 43 | @tasks.loop(seconds=10, overlap=2)
|
43 | 44 | async def fetch_status_task(self):
|
44 | 45 | """
|
45 | 46 | Practical overlap use-case:
|
46 | 47 |
|
47 | 48 | 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 |
49 | 50 | every 10s. Allowing a small amount of overlap avoids drifting schedules
|
50 | 51 | without opening the floodgates to unlimited concurrency.
|
51 | 52 | """
|
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}") |
54 | 54 |
|
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)) |
57 | 57 |
|
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) |
60 | 64 |
|
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}") |
69 | 66 |
|
70 | 67 |
|
71 | 68 | client = MyClient()
|
|
0 commit comments