1. 程式人生 > >python 64式: 第6式、定時器

python 64式: 第6式、定時器

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

import logging
import sys

from datetime import datetime
from oslo_config import cfg
from oslo_log import log
from oslo_service import service

'''
關鍵:
1 編寫的定時任務需要繼承oslo_service.service類,實現start方法,
start方法是主入口
    def start(self):
        delay_timers = 3
        self.tg.add_timer(self.period, self.runTask, delay_timers)
上述self.tg.add_timer的引數分別是:
self.period: 定時任務的時間間隔
self.runTask: 定時執行的方法
delay_timers:首次執行的延遲啟動時間,即延遲指定時間,開啟第一次定時任務

參考:
https://docs.openstack.org/oslo.service/latest/user/history.html
'''

LOG = logging.getLogger(__name__)

OPTS = [
    cfg.IntOpt('period',
               default=10,
               help='scan interval'),
]

CONF = cfg.CONF
CONF.register_opts(OPTS)


def timeHelper(func):
    def wrapper(*args, **kwargs):
        try:
            start = datetime.now()
            info = "############ Begin task, start: %s ##########" % (
                str(start))
            LOG.info(info)
            func(*args, **kwargs)
            end = datetime.now()
            diff = end - start
            info = "##### End task, end: %s, cost time: %s #####" % (
                str(end), str(diff))
            LOG.info(info)
        except Exception as ex:
            info = "Exception type is %s, message is %s" % (ex.__class__.__name__, ex)
            LOG.error(info)
    return wrapper


class MyTask(service.Service):

    def __init__(self, *args, **kwargs):
        super(MyTask, self).__init__(*args, **kwargs)
        self.period = CONF.period

    def process(self):
        print "process task"

    @timeHelper
    def runTask(self):
        self.process()

    def start(self):
        delay_timers = 3
        self.tg.add_timer(self.period, self.runTask, delay_timers)


def prepare_service():
    log.register_options(CONF)
    log.set_defaults(default_log_levels=CONF.default_log_levels)
    log.setup(CONF, 'myapp')


def main():
    prepare_service()
    cfg.CONF(sys.argv[1:], project='myapp')
    service.launch(CONF, MyTask()).wait()

if __name__ == "__main__":
    main()