[Twisted-Python] Problems with deferred

Thomas Weholt 2002 at weholt.org
Mon Jul 7 18:30:43 EDT 2003


I got a tip earlier from this list on how to implement a scheduled task, or
in my case several task. I want my ApplicationService-object to hold a list
of tasks, looking somewhat like the ones subclassing the task-class in the
code below, where a method called Action is called on a given interval. I
want users to be able to just subclass my task-class and override the
action-method and then the application will create a list of instances of
these tasks, call their start method and from there on their action method
will be called over and over on the intervall specified in their
refreshInterval-attribute given at creation.

Does that makes sense? In my code only Task1.action is called, and
Task2.action is called just before the thing exits. Why?

Any hints?

from twisted.internet.app import Application, ApplicationService
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log

class task:

    def __init__(self, service, refreshInterval=5):
        self.service = service
        self.refreshInterval = refreshInterval

    def start(self):
        reactor.callLater(self.refreshInterval, self.execute)

    def action(self):
        "Override this!"
        print "action called"

    def execute(self):
        d = defer.Deferred()
        reactor.callLater(0, self.action)

        # Log any errors in downloading or processing

        # Reschedule this function
        d.addBoth(reactor.callLater, self.refreshInterval, self.execute)

class task1(task):
    def action(self):
        print "Task 1 called"

class task2(task):
    def action(self):
        print "Task 2 called"

class testservice(ApplicationService):

    def __init__(self, application):
        self.application = application
        self.tasks = [task1(self), task2(self)]

    def startService(self):
        print "Starting services"
        for task in self.tasks:

    def stopService(self):
        print "Stopping services"

app = Application('test app')
srv = testservice(app)

Best regards,
Thomas W

More information about the Twisted-Python mailing list