Skip to content

Commit 68041ce

Browse files
committed
- make tasks be a set of asyncio.Task and auto-discarded when done
- add a timeout of 100 milliseconds that doesn't block the code and accepts new jobs
1 parent b4f844d commit 68041ce

1 file changed

Lines changed: 8 additions & 12 deletions

File tree

runpod/serverless/modules/rp_scale.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,9 @@ async def run_jobs(self, session: ClientSession):
216216
217217
Runs the block in an infinite loop while the worker is alive or jobs queue is not empty.
218218
"""
219-
tasks = [] # Store the tasks for concurrent job processing
219+
tasks: set[asyncio.Task] = set() # Store the tasks for concurrent job processing
220220

221221
while self.is_alive() or not self.jobs_queue.empty() or tasks:
222-
# log.debug(f"Task count: {len(tasks)}, Queue size: {self.jobs_queue.qsize()}, Concurrency: {self.current_concurrency}")
223222
# Fetch as many jobs as the concurrency allows
224223
while len(tasks) < self.current_concurrency and not self.jobs_queue.empty():
225224
# log.debug(f"About to get a job from the queue. Queue size: {self.jobs_queue.qsize()}")
@@ -229,18 +228,15 @@ async def run_jobs(self, session: ClientSession):
229228

230229
# Create a new task for each job and add it to the task list
231230
task = asyncio.create_task(self.handle_job(session, job))
232-
tasks.append(task)
231+
tasks.add(task)
232+
task.add_done_callback(tasks.discard)
233233

234-
# Prune completed tasks
235-
tasks = [t for t in tasks if not t.done()]
236-
237-
if tasks or not self.jobs_queue.empty():
238-
# Work is active → check often for new jobs
239-
await asyncio.sleep(0.5)
234+
# 2. If jobs are running, wait a little for completions
235+
if tasks:
236+
await asyncio.wait(tasks, timeout=0.1, return_when=asyncio.FIRST_COMPLETED)
240237
else:
241-
# Fully idle → sleep longer to save CPU
242-
log.info("No jobs running, sleeping for 1 second.")
243-
await asyncio.sleep(1)
238+
# Nothing running — don’t spin CPU
239+
await asyncio.sleep(0.5)
244240

245241
# Ensure all remaining tasks finish before stopping
246242
await asyncio.gather(*tasks)

0 commit comments

Comments
 (0)