zoukankan      html  css  js  c++  java
  • python twisted启动定时服务

    以下是python脚本send_mms.py

    ############################################
    #!/usr/bin/python
    # -*- coding: utf-8 -*-

    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

  • 相关阅读:
    [POJ]poj2632(模拟)
    [EOJ]2019 ECNU XCPC March Selection #2
    [POJ]POJ1328(trie)
    卡特兰数相关总结
    2019海亮夏令营随笔
    树上数数 题解
    护卫小队 题解
    洛谷 P2966 [USACO09DEC]牛收费路径Cow Toll Paths 题解
    洛谷 P4735 最大异或和
    登峰造极 题解
  • 原文地址:https://www.cnblogs.com/weiok/p/5107861.html
Copyright © 2011-2022 走看看