python创建一个异步计时器,不等待完成



我想创建一个在正常函数中启动的计时器,但在计时器函数中,它应该能够调用异步函数

我想这样做:

startTimer()
while True:
print("e")
def startTimer(waitForSeconds: int):
# Wait for `waitForSeconds`
await myAsyncFunc()
async def myAsyncFunc():
print("in my async func")

while True循环应该做它的事情,waitForSeconds计时器之后,异步函数应该执行另一个异步函数,但是等待不应该阻塞任何其他动作,也不需要等待

如果有什么不明白的地方,我很抱歉,我会尽力解释的。

感谢

如果您想并行运行同步和异步代码,则需要在单独的线程中运行其中一个。例如:

def sync_code():
while True:
print("e")
async def start_timer(secs):
await asyncio.sleep(secs)
await async_func()
async def main():
asyncio.create_task(start_timer(1))
loop = asyncio.get_event_loop()
# use run_in_executor to run sync code in a separate thread
# while this thread runs the event loop
await loop.run_in_executor(None, sync_code)
asyncio.run(main())

如果上面的方法对你来说是不可接受的(例如,因为它把整个程序变成了asyncio程序),你也可以在后台线程中运行事件循环,并使用asyncio.run_coroutine_threadsafe向它提交任务。这种方法将允许startTimer拥有您想要的签名(和接口):

def startTimer(waitForSeconds):
loop = asyncio.new_event_loop()
threading.Thread(daemon=True, target=loop.run_forever).start()
async def sleep_and_run():
await asyncio.sleep(waitForSeconds)
await myAsyncFunc()
asyncio.run_coroutine_threadsafe(sleep_and_run(), loop)
async def myAsyncFunc():
print("in my async func")
startTimer(1)
while True:
print("e")

我很确定您对并发处理很熟悉,但是您并没有确切地说明您想要什么。如果我没理解错的话你想要有两个过程。第一个是只做while True,第二个进程是定时器(等待例如5秒),它将调用异步任务。我假设您根据标签使用asyncio:

import asyncio
async def myAsyncFunc():
print("in my async func")
async def call_after(delay):
await asyncio.sleep(delay)
await myAsyncFunc()
async def while_true():
while True:
await asyncio.sleep(1) # sleep here to avoid to large output
print("e")
async def main():
task1 = asyncio.create_task(
while_true())
task2 = asyncio.create_task(
call_after(5))
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
asyncio.run(main())