Execute a background task with timeout and error handling.
(self, task: BackgroundTask)
| 135 | return True |
| 136 | |
| 137 | async def _run_task(self, task: BackgroundTask): |
| 138 | """Execute a background task with timeout and error handling.""" |
| 139 | try: |
| 140 | # Run the task function |
| 141 | if asyncio.iscoroutinefunction(task.func): |
| 142 | await asyncio.wait_for(task.func(), timeout=task.timeout) |
| 143 | else: |
| 144 | # Run sync function in executor |
| 145 | loop = asyncio.get_event_loop() |
| 146 | await loop.run_in_executor(None, task.func) |
| 147 | |
| 148 | task.status = BackgroundTaskStatus.COMPLETED |
| 149 | task.stopped_at = time.time() |
| 150 | success(f"Background: completed task '{task.name}'") |
| 151 | |
| 152 | except asyncio.TimeoutError: |
| 153 | task.status = BackgroundTaskStatus.FAILED |
| 154 | task.error = f"Timeout after {task.timeout}s" |
| 155 | error(f"Background: task '{task.name}' timed out") |
| 156 | |
| 157 | except asyncio.CancelledError: |
| 158 | task.status = BackgroundTaskStatus.STOPPED |
| 159 | task.stopped_at = time.time() |
| 160 | info(f"Background: stopped task '{task.name}'") |
| 161 | |
| 162 | except Exception as e: |
| 163 | task.status = BackgroundTaskStatus.FAILED |
| 164 | task.error = str(e) |
| 165 | task.stopped_at = time.time() |
| 166 | error(f"Background: task '{task.name}' failed: {e}") |
| 167 | |
| 168 | def stop_task(self, task_id: str) -> bool: |
| 169 | """ |
no test coverage detected