Python 基于 Timer 实现定时周期执行函数的封装方法
本文介绍了一种基于 Python threading.Timer 的封装方案,用于实现函数在指定时间间隔内周期性执行。通过自定义 MyTimer 类,解决了传统 Timer 需手动重启的问题,支持指定启动时间、执行间隔及回调参数,适用于需要固定频率触发特定逻辑的场景。
在项目开发过程中,遇到一个具体的需求挑战:
需要让某个特定函数在每个小时的第 3 分钟准时执行一次。假设程序在 15:45 启动,期望它在经过 18 分钟后,于 16:03 首次执行;随后每隔 60 分钟,分别在 17:03、18:03 等时间点重复执行该函数。
基于 Python 的 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()
以上关于 Python 实现功能周期性执行的封装方法即为本文分享的全部内容,希望能为读者提供有价值的参考,同时也欢迎大家继续支持本站获取更多技术资源。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









