Tuesday, August 24, 2010

Learning Twisted (part 3) : Scheduling with reactor

In previous installments, we found that twisted does provide methods to schedule a call at some time later, after the reactor loop starts running. It also provides method for registering a call that will be called repeatedly after a delay.

The facility is provided in twisted.internet.task.

from twisted.internet import reactor
from twisted.python import log
import sys, time
from twisted.internet.task import LoopingCall, deferLater


We schedule to call loopedFunction every two seconds and stop this loop after eight seconds.

iterVal = 0

def loopedFunction():
    global iterVal
    iterVal = iterVal + 1
    now = time.localtime(time.time())
    timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now))
    log.msg(timeStr + " : iteration : " + str(iterVal))
def cancelLoop(loopObj):
    log.msg("Called cancelLoop")
    log.msg("Loop object has been stopped")
    log.msg("Shutting down the reactor")
now = time.localtime(time.time())
timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now))
log.msg("will call loopedFunction, every 2 second")

The following gives you a loop object which can be started, stopped or delayed.
Here, we also provide a mechanism to place a call that will stop the looping call. There are two ways to schedule a call at some time later - deferLater or callLater

loopObj = LoopingCall(loopedFunction)
loopObj.start(2, now=True)

defObj = deferLater(reactor, 8, cancelLoop, loopObj)
# We could also have used callLater
#reactor.callLater(8, cancelLoop, loopObj)

No comments:

Post a Comment