python twisted启动定时服务

以下是python脚本send_mms.py

############################################

from twisted.application import service

from twisted.internet import reactor

def main(counter=0):

    print counter, '...'

    if counter == 10:

        reactor.stop()

    else:

        reactor.callLater(60, main, counter+1)   # 1分钟执行一次

    

if __name__ == "__main__":

    reactor.callLater(1, main)

    print 'Start!'

    reactor.run()

    print 'Stop!'

elif __name__=='__builtin__':

    print '__builtin__'

    reactor.callLater(1, main)

    application=service.Application('send_mms')

############################################

shell 启动服务脚本send_mms.sh

############################################

#! /usr/bin/env sh  

MAIN_MODULE=loop_mms

case $1 in  

    start)  

        PYTHONPATH=.:$PYTHONPATH twistd --python=$MAIN_MODULE.py --pidfile=/var/run/$MAIN_MODULE.pid --logfile=log/$MAIN_MODULE_client.log

        ;;  

    stop)  

        kill -9 `cat /var/run/$MAIN_MODULE.pid`  

        ;;  

    restart)  

        kill -9 `cat /var/run/$MAIN_MODULE.pid`  

        sleep 1  

        PYTHONPATH=.:$PYTHONPATH twistd --python=$MAIN_MODULE.py --pidfile=/var/run/$MAIN_MODULE.pid --logfile=log/$MAIN_MODULE_client.log  

        ;;  

    log)  

        tail -f log/$MAIN_MODULE_client.log

        ;;  

    *)  

        echo "Usage: ./$MAIN_MODULE.py start | stop | restart | log"  

        ;;  

esac  

############################################

现在测试另一种情况,既然twisted 以callback的方法来执行我们的方法,你会想如果一个callback抛出了异常怎么办.让我们试试吧,basic-twisted/exception.py会在一个callback中抛出一个异常:

def falldown():

    raise Exception('I fall down.')

def upagain():

    print 'But I get up again.'

    reactor.stop()

from twisted.internet import reactor

reactor.callWhenRunning(falldown)

reactor.callWhenRunning(upagain)

print 'Starting the reactor.'

reactor.run()

你会看到以下输出:

Starting the reactor.

Traceback (most recent call last):

  ... # I removed most of the traceback

exceptions.Exception: I fall down.

But I get up again.

注意第二个callback仍会在第一个callback之后运行,即使我们看到了很多的异常的追踪信息.如果你把reactor.stop()注释掉的话,这个程序会仍会继续运行下去,所以reactor 会继续运行下去即使我们的一个callback抛出了异常。

文章部分内容参考:http://floss.zoomquiet.io/data/20110709133658/index.html

原文地址:https://www.cnblogs.com/weiok/p/4875481.html