我有一个实用程序类,用于计划要在timeout
秒内执行的作业:
class AsyncTimer:
def __init__(self, timeout, callback):
self._timeout = timeout
self._callback = callback
self._task = asyncio.ensure_future(self._job())
async def _job(self):
await asyncio.sleep(self._timeout)
await self._callback()
我也有一个类似于以下内容的状态机:
class IState(metaclass=abc.ABCMeta):
def __init__(self, machine):
self._machine = machine
# The OnState can only transition into the TurningOffState, etc...
class OnState(IState):
def __init__(self, machine):
super().__init__(machine)
print("Turned on!")
def turnOff(self):
self.__machine.currentState = TurningOffState(self._machine)
class OffState(IState):
def __init__(self, machine):
super().__init__(machine)
print("Turned off!")
def turnOn(self):
self.__machine.currentState = TurningOnState(self._machine)
# Transition state that has no state transitions. automaticly transitions to `OnState` after 2 secconds
class TurningOnState(IState):
async def _callback(self):
self._machine.currentState = OnState(self._machine)
def __init__(self, machine):
super().__init__(machine)
print("Turning on!")
self.__timer = AsyncTimer(2, self._callback)
我有一个包含当前活动状态的对象:
class FSM:
def __init__(self):
self.currentState = OffState(self)
def __del__(self):
print("destroying FSM")
我的主循环如下:
async def main():
fsm = FSM()
fsm.currentState.turnOn()
# fsm gets destroyed here, along with currently contained state which may have a pending task. How do I fix this?
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
这将输出:
Turned Off!
Turning On!
destroying FSM
Task was destroyed but it is pending!
task: <Task pending coro=<AsyncTimer._job() done, defined at pythreadtest.py:11> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f0c1d891258>()]>>
我很确定问题是打开请求后,FSM以及当前包含的状态(可能有待处理的任务)都被销毁了。
我该如何解决?我可以在析构函数中放一些东西来等待所有未完成的任务完成吗?我该怎么办?我的设计还有其他问题吗?
谢谢
编辑
我尝试在转换请求后添加sleep
。这解决了我的问题,但是如果FSM可以原子性地sleep
销毁所有任务,直到完成所有任务。
fsm = DoorFSM()
fsm.currentState.openDoor()
await asyncio.sleep(3)
edit2
另一种解决方案是公开task
中的AsyncTimer
,然后在过渡状态中公开它。即:
def __init__(self, machine):
super().__init__(machine)
print("Turning On")
self.__timer = AsyncTimer(2, self._callback)
self.task = self.__timer.task
然后,主循环可以等待wait
结束该任务
fsm = DoorFSM()
fsm.currentState.openDoor()
await asyncio.wait({fsm.currentState.task})
但是如果我可以将其放在FSM
的析构函数中,我会更喜欢它,但是它不会让我在析构函数中等待。