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设计】。

相关文章

介绍Python中的一些高级编程技巧

 正文: 本文展示一些高级的Python设计结构和它们的使用方法。在日常工作中,你可以根据需要选择合适的数据结构,例如对快速查找性的要求、对数据一致性的要求或是对索引的要求等,...

python验证码识别教程之滑动验证码

前言 上篇文章记录了2种分割验证码的方法,此外还有一种叫做”滴水算法”(Drop Fall Algorithm)的方法,但本人智商原因看这个算法看的云里雾里的,所以今天记录滑动验证码的处...

python检测空间储存剩余大小和指定文件夹内存占用的实例

1、检测指定路径下所有文件所占用内存 import os def check_memory(path, style='M'): i = 0 for dirpath, dirnam...

Python中asyncio与aiohttp入门教程

Python中asyncio与aiohttp入门教程

很多朋友对异步编程都处于“听说很强大”的认知状态。鲜有在生产项目中使用它。而使用它的同学,则大多数都停留在知道如何使用 Tornado、Twisted、Gevent 这类异步框架上,出现...

基于django channel实现websocket的聊天室的方法示例

websocket 网易聊天室? ​ web微信? ​ 直播? 假如你工作以后,你的老板让你来开发一个内部的微信程序,你...