Mercurial
comparison async_multi_threads/job_scheduler.py @ 69:551d9fc0a2ba
Updated wrong names.
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Thu, 25 Dec 2025 20:07:46 -0800 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 68:70ca1d99f3fd | 69:551d9fc0a2ba |
|---|---|
| 1 # Job Schedular | |
| 2 # | |
| 3 # Implement a concurrent job scheduler that can schedule multiple workers to complete job tasks. The scheduler must handle asynchronous tasks and be able to dynamically increase or decrease the number of workers. It must handle task execution failures, for example, by retrying or logging. Provide examples with at least three different tasks and examples of scheduling strategies. | |
| 4 | |
| 5 import asyncio | |
| 6 from asyncio import Task | |
| 7 import random | |
| 8 | |
| 9 # Rename to match standard library function | |
| 10 async def job(name: str, delay: int = 1): | |
| 11 # Use asyncio.sleep | |
| 12 await asyncio.sleep(delay) | |
| 13 val = random.randint(1, 10) | |
| 14 if val > 5: | |
| 15 raise Exception("Something went wrong") | |
| 16 else: | |
| 17 print(name) | |
| 18 | |
| 19 class JobScheduler: | |
| 20 def __init__(self): | |
| 21 self._jobs: list[Task] = [] | |
| 22 | |
| 23 def add_task(self, task: Task): | |
| 24 self._jobs.append(task) | |
| 25 print(f"Added job: {task.get_name()}") # Added for debugging | |
| 26 | |
| 27 async def run(self): | |
| 28 print("Starting concurrent jobs...") | |
| 29 await asyncio.gather(*self._jobs, return_exceptions=True) | |
| 30 print("All jobs completed.") | |
| 31 | |
| 32 async def main(): | |
| 33 job_scheduler = JobScheduler() | |
| 34 # Use asyncio.create_task and provide a name | |
| 35 job_scheduler.add_task(asyncio.create_task(job("JUNE", 3), name="JUNE_JOB")) | |
| 36 job_scheduler.add_task(asyncio.create_task(job("PARK", 2), name="PARK_JOB")) | |
| 37 job_scheduler.add_task(asyncio.create_task(job("HELLO", 1), name="HELLO_JOB")) | |
| 38 await job_scheduler.run() | |
| 39 | |
| 40 | |
| 41 if __name__ == "__main__": | |
| 42 # Run the main asynchronous entry point | |
| 43 asyncio.run(main()) |