Python 实现某个功能每隔一段时间被执行一次的功能

本人在做项目的时候遇到一个问题:
某个函数需要在每个小时的 3 分钟时候被执行一次,我希望我 15:45 启动程序,过了18 分钟在 16:03 这个函数被执行一次,下一次过 60 分钟在 17:03 再次被执行,下一次 18:03,以此类推。
以下是我基于 Timer 做的再封装实现了此功能。

# -*- coding: utf-8 -*-
# ==================================================
# 对 Timer 做以下再封装的目的是:当某个功能需要每隔一段时间被
# 执行一次的时候,不需要在回调函数里对 Timer 做重新安装启动
# ==================================================
__author__ = 'liujiaxing'

from threading import Timer
from datetime import datetime

class MyTimer( object ):

    def __init__( self, start_time, interval, callback_proc, args=None, kwargs=None ):

        self.__timer = None
        self.__start_time = start_time
        self.__interval = interval
        self.__callback_pro = callback_proc
        self.__args = args if args is not None else []
        self.__kwargs = kwargs if kwargs is not None else {}

    def exec_callback( self, args=None, kwargs=None ):
        self.__callback_pro( *self.__args, **self.__kwargs )
        self.__timer = Timer( self.__interval, self.exec_callback )
        self.__timer.start()

    def start( self ):
        interval = self.__interval - ( datetime.now().timestamp() - self.__start_time.timestamp() )
        print( interval )
        self.__timer = Timer( interval, self.exec_callback )
        self.__timer.start()

    def cancel( self ):
        self.__timer.cancel() 
        self.__timer = None

class AA:
    def hello( self, name, age ):
        print( "[%s]\thello %s: %d\n" % ( datetime.now().strftime("%Y%m%d %H:%M:%S"), name, age ) )

if __name__ == "__main__":

    aa = AA()
    start = datetime.now().replace( minute=3, second=0, microsecond=0 )
    tmr = MyTimer( start, 60*60, aa.hello, [ "owenliu", 18 ] )
    tmr.start()
    tmr.cancel()
  • 12
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值