[Twisted-Python] Cleanly shutting down Service

Eric Mangold teratorn at twistedmatrix.com
Mon Apr 3 02:02:18 EDT 2006

On Mon, 03 Apr 2006 13:01:07 +1000, Reed L. O'Brien <reed at intersiege.com>  

> Jean-Paul Calderone wrote:
>> On Sun, 02 Apr 2006 21:30:06 -0400, "Reed L. O'Brien"
>> <reed at intersiege.com> wrote:
>>> apocalypznow wrote:
>>>> How do I cleanly shut down a Service?  I want the shut down to make
>>>> the stopService() method get called.
>>> import signal, sys
>>> signal.signal(signal.SIGINT, handler)
>>> def handler(signum, frame):
>>>    print "Shutting down the Foo service" # or use a logging facility
>>>    stopService()
>>>    sys.exit(2)
>>> Will catch ^C and call handler for more read the signal docs:
>>> http://www.python.org/doc/current/lib/module-signal.html
>> Alas, this won't do anything resembling correct in a Twisted  
>> application.
>> I tried to come up with an answer to this question earlier today, but
>> failed: perhaps the OP can ask a more specific or detailed one which
>> will be easier to answer correctly.
>> Jean-Paul
> reactor.addSystemEventTrigger('before', 'shutdown', func())
> def func():
> 	doStuff...
> closer?
> ~reed

Not really, No. I think you should have waited for the OP to ask a better  
question as JP suggested. The quality of questions on this mailing list  
has been very poor lately. Anyway, onwards...

To shut down a Service cleanly, you call stopService() on it.

If you want your service to have its stopService method called when  
Twisted shuts down, then
that service should be registered correctly. If you aren't using twistd  
then see

>>> An example test.tac file:

 from twisted.application import service

class MyService(service.Service):
     def stopService(self):
         print "Stopping my service!"

application = service.Application("My Twisted App")
myService = MyService()
myService.setName("My Service")

 from twisted.internet import reactor
reactor.callLater(2, reactor.stop)

<<< End test.tac

If you run the .tac file with "twistd -noy test.tac", after 2 seconds,
you will see "Stopping my service!" printed.


More information about the Twisted-Python mailing list