giambio/giambio/context.py

66 lines
1.8 KiB
Python
Raw Normal View History

2020-11-14 10:42:46 +01:00
"""
Copyright (C) 2020 nocturn9x
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
2020-11-16 08:07:19 +01:00
2020-11-14 10:42:46 +01:00
import types
2020-11-16 08:07:19 +01:00
from .core import AsyncScheduler
from .objects import Task
2020-11-14 10:42:46 +01:00
class TaskManager:
"""
An asynchronous context manager for giambio
"""
def __init__(self, loop: AsyncScheduler) -> None:
"""
Object constructor
"""
self.loop = loop
2020-11-16 08:07:19 +01:00
self.tasks = []
2020-11-14 10:42:46 +01:00
def spawn(self, func: types.FunctionType, *args):
"""
Spawns a child task
"""
2020-11-16 08:07:19 +01:00
task = Task(func(*args), func.__name__ or str(func))
task.parent = self.loop.current_task
2020-11-14 10:42:46 +01:00
self.loop.tasks.append(task)
2020-11-16 08:07:19 +01:00
self.tasks.append(task)
2020-11-14 10:42:46 +01:00
def spawn_after(self, func: types.FunctionType, n: int, *args):
"""
Schedules a task for execution after n seconds
"""
assert n >= 0, "The time delay can't be negative"
2020-11-16 08:07:19 +01:00
task = Task(func(*args), func.__name__ or str(func))
task.parent = self.loop.current_task
2020-11-14 10:42:46 +01:00
self.loop.paused.put(task, n)
2020-11-16 08:07:19 +01:00
self.tasks.append(task)
2020-11-14 10:42:46 +01:00
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
2020-11-16 08:07:19 +01:00
for task in self.tasks:
2020-11-14 10:42:46 +01:00
try:
await task.join()
2020-11-16 21:49:13 +01:00
except BaseException:
for to_cancel in self.tasks:
await to_cancel.cancel()