選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

36 行
1015 B

  1. import asyncio
  2. import typing
  3. from starlette.concurrency import run_in_threadpool
  4. class BackgroundTask:
  5. def __init__(
  6. self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any
  7. ) -> None:
  8. self.func = func
  9. self.args = args
  10. self.kwargs = kwargs
  11. self.is_async = asyncio.iscoroutinefunction(func)
  12. async def __call__(self) -> None:
  13. if self.is_async:
  14. await self.func(*self.args, **self.kwargs)
  15. else:
  16. await run_in_threadpool(self.func, *self.args, **self.kwargs)
  17. class BackgroundTasks(BackgroundTask):
  18. def __init__(self, tasks: typing.Sequence[BackgroundTask] = None):
  19. self.tasks = list(tasks) if tasks else []
  20. def add_task(
  21. self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any
  22. ) -> None:
  23. task = BackgroundTask(func, *args, **kwargs)
  24. self.tasks.append(task)
  25. async def __call__(self) -> None:
  26. for task in self.tasks:
  27. await task()