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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值