I have a work()
method that calls functions that may invoke time.sleep
. This clearly goes against recommended twisted usage.
Suppose one could replace LoopingCall with threads.deferToThread()
and loop manually in our worker, but are there alternative ways to accomplish this while still utilizing LoopingCall?
Pseudocode:
from twisted.internet.task import LoopingCall
looping_call = LoopingCall(work)
looping_call.start(10)
def work():
result = False
for i in elements:
if blocking_function(i): # note processing sequentially here is preferred
result = True
if result:
dosomething()
def blocking_function(i):
time.sleep(5)
return True # or False
One solution is to use deferToThread
only for the blocking call:
async def work():
result = False
for i in elements:
# note processing sequentially here is preferred
if await deferToThread(lambda: blocking_function(i)):
result = True
if result:
dosomething()