首页 > 解决方案 > Asyncio .create_task() 未运行传入的函数

问题描述

我正在尝试制作一个在 python 中执行几个与计时器相关的事情的程序,我需要制作它,以便 Asyncio 通过调用另一个函数来创建一个任务(而不等待它)asyncio.get_event_loop().create_task(timer_function(my_parameters)),我之前在另一个项目中使用过它并且它工作得很好,但是,在这种情况下,它最终没有timer_function()像它应该的那样调用,我怀疑它发生是因为它在循环内部或与项目结构相关的东西。我现在找不到任何可以正常工作的东西,只能使用awaitmanaged 来调用该函数,但这最终并没有使它并行运行。项目结构如下:

async def timer_function(my_parameters):

   print('Timer_Function called')
   
   # Do stuff with the parameters

   asyncio.sleep(time_based_on_those_parameters)

   # Finish doing some other things



# Note: final() doesn't need to be async, I only made it so
# to try and test some fixes
async def final(parameters):  

   # Do stuff

   while True:  # This part loops forever every minute

      # Do stuff

      for i in range(my_range):

         if some_condition_a:

            asyncio.get_event_loop().create_task(timer_function(my_parameters))

            print('Condition A met')

         if some_condition_b:

            asyncio.get_event_loop().create_task(timer_function(some_different_parameters)

            print('Condition B met')

         # Do some other stuff

   sleep(60)

一旦我运行代码,满足这些条件时打印的所有内容都是

>>> Condition met

但我期望看到的是

>>> Condition met
>>> Timer function called

然后我把当时await打印的所有内容放在 create_task 部分之前

>>> Timer function called

然后只有当计时器用完并完成它需要做的事情时才>>> Condition met 被打印出来。有没有办法改变这个结构以适应 Asyncio 或我可以尝试的其他东西?

编辑:我找到了一种解决方法,使用threading而不是asyncio. 代码现在是这样的:

def timer_function(my_parameters): # Sync method now

   print('Timer_Function called')
   
   # Do stuff with the parameters

   sleep(time_based_on_those_parameters) # No longer asyncio.sleep()

   # Finish doing some other things



def final(parameters):  

   # Do stuff

   threads = []

   while True:  # This part loops forever every minute

      # Do stuff

      for i in range(my_range):

         if some_condition_a:

             t = threading.Thread(target=timer_function, args=(my_parameters))
             threads.append(t)
             t.start()          

             print('Condition A met')

         if some_condition_b:

            t = threading.Thread(target=timer_function, args=(my_parameters))
            threads.append(t)
            t.start()

            print('Condition B met')

         # Do some other stuff

   sleep(60)

这现在按预期工作,所以对我来说,我不再需要解决这个问题,但是如果有人知道为什么 Asyncio 在这种结构中不这样做,请告诉我,因为将来有人可能会遇到同样的问题。(我检查了我制作的另一个项目, asyncio.get_event_loop().create_task(timer_function(my_parameters)) 可以在不等待的情况下调用,不同之处在于在这种情况下它在一个while True和一个for循环内,而在这种情况下,它只是在事件侦听器上调用一次)

标签: pythonpython-asyncio

解决方案


我才开始使用 asyncio 但我的猜测是它没有create_task运行任何东西,你可以尝试run_until_complete


推荐阅读