alexpirine
alexpirine

Reputation: 3283

Twisted web server: execute a deferred action after sending response

I have a simple web service defined as:

from twisted.internet import endpoints
from twisted.internet import reactor
from twisted.web import resource
from twisted.web import server

class TestService(resource.Resource):
    def render_GET(self, request):
        return "ok"

ts = TestService()
endpoints.serverFromString(reactor, "tcp:{}".format(8080)).listen(server.Site(ts))
reactor.run()

This service always sends ok on every GET request.

Fine.

But I need to execute a deferred action 1 minute after the request has been processed.

How do I do it?

I mean something like this:

from twisted.internet import endpoints
from twisted.internet import reactor
from twisted.web import resource
from twisted.web import server

def deferred_action():
    time.sleep(60)
    # do some action...
    print("action completed")

class TestService(resource.Resource):
    def render_GET(self, request):
        defer(deferred_action) # how do I do this?
        return "ok"

ts = TestService()
endpoints.serverFromString(reactor, "tcp:{}".format(8080)).listen(server.Site(ts))
reactor.run()

Upvotes: 0

Views: 97

Answers (1)

Klaus D.
Klaus D.

Reputation: 14404

You can use the callLater() method of the reactor:

reactor.callLater(60.0, deferred_action)

You can also add more arguments which would then be passed into the deferred_action function. Of course it will need to accept them.

def deferred_action(value):
    print(value)

class TestService(resource.Resource):
    def render_GET(self, request):
        reactor.callLater(60.0, deferred_action, 'some value')

Upvotes: 1

Related Questions