Код: Выделить всё
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
Код: Выделить всё
>>> Timer function called
. Есть ли способ изменить эту структуру, чтобы разместить Asyncio или что-то еще, что я мог бы попробовать?
EDIT: я нашел обходной путь, используя многопоточность вместо асинхронно. Код теперь такой:
Код: Выделить всё
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.get_event_loop().create_task(timer_function(my_parameters))
Подробнее здесь: https://stackoverflow.com/questions/689 ... -passed-in