zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    JDK8的JVM内存模型小结
    揭开Service Mesh的神秘面纱
    通过Shell脚本读取properties文件中的参数时遇到 换行符的问题
    NodeJs+Express实现简单的Web增删改查
    SpringBoot之Thymeleaf模板引擎
    面向对象(下)
    内部类
    线程学习oneday
    Python-使用tkinter实现的Django服务进程管理工具
    Python-使用百度文字识别API实现的文字识别工具
  • 原文地址:https://www.cnblogs.com/weiok/p/4875481.html
Copyright © 2011-2022 走看看