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)

1 comment:

  1. Tradingzy is the best and most reliable Seo company And offers a wide variety of Link Fx Seo , including an affordable monthly subscription service, one-time links, and blog comments. With any of these services, you can be assured that your site will rank higher in the search engine results page and receive an influx of targeted traffic.