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

  • 相关阅读:
    HDU 4034 Graph:反向floyd
    POJ 2728 Desert King:最优比率生成树
    求树的最大独立集,最小点覆盖,最小支配集 贪心and树形dp
    AtCoder ARC061E Snuke's Subway Trip 最短路
    hdu4126_hdu4756_求最小生成树的最佳替换边_Kruskal and Prim
    洛谷 P2633 Count on a tree
    POJ3241 最小曼哈顿距离生成树
    HDU6315 Naive Operations 线段树
    ACM-ICPC 2018 沈阳赛区网络预赛-B,F,G
    LCA
  • 原文地址:https://www.cnblogs.com/weiok/p/5107861.html
Copyright © 2011-2022 走看看