Use deferred to create an endless call loop

Is it possible to use deferred ( http://twistedmatrix.com/documents/current/core/howto/defer.html ) to create an infinite call loop in which the function adds itself to the deferred chain? I tried to do this, but this does not work:

d = deferred.Deferred()
first = True

def loopPrinting(dump):
  ch = chr(random.randint(97, 122))
  print ch
  global d, first
  d.addCallback(loopPrinting)
  if first:
    d.callback('a')
    first = False
  return d

loopPrinting('a')

reactor.run()
+3
source share
1 answer

This is not acceptable for Deferral. Instead, try using reactor.callLater:

from twisted.internet import reactor

def loopPrinting():
    print chr(random.randint(97, 122))
    reactor.callLater(1.0, loopPrinting)

loopPrinting()
reactor.run()

Or twisted.internet.task.LoopingCall:

from twisted.internet import task, reactor

def loopPrinting():
    print chr(random.randint(97, 122))

loop = task.LoopingCall(loopPrinting)
loop.start(1.0)
reactor.run()

. -, , . ( a) ( b) -, "". b , a . , a b , .

-, , , . . . , , d.addCallback(loopPrinting). , .

+5

Source: https://habr.com/ru/post/1757716/


All Articles