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

yipeiwu_com5年前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()

以上这篇Python 实现某个功能每隔一段时间被执行一次的功能方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

对Django中static(静态)文件详解以及{% static %}标签的使用方法

在一个网页中,不仅仅只有一个html骨架,还需要css样式文件,js执行文件以及一些图片等。因此在DTL中加载静态文件是一个必须要解决的问题。在DTL中,使用static标签来加载静态文...

Python和GO语言实现的消息摘要算法示例

Python和GO语言实现的消息摘要算法示例

常用的消息摘要算法有MD5和SHA,这些算法在python和go的库中都有,需要时候调用下就OK了,这里总结下python和go的实现。 一、python消息摘要示例 代码如下: 复制代...

python简单实现旋转图片的方法

本文实例讲述了python简单实现旋转图片的方法。分享给大家供大家参考。具体实现方法如下: # rotate an image counter-clockwise using the...

python3实现随机数

python3实现随机数

Python3实现随机数,供大家参考,具体内容如下 random是用于生成随机数的,我们可以利用它随机生成数字或者选择字符串。 random.seed(x)改变随机数生成器的种子seed...

Python实现绘制双柱状图并显示数值功能示例

Python实现绘制双柱状图并显示数值功能示例

本文实例讲述了Python实现绘制双柱状图并显示数值功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #! python3 import matp...