Python 实现某个功能每隔一段时间被执行一次的功能方法
作者:独一无二的小个性 时间:2021-11-14 09:57:25
本人在做项目的时候遇到一个问题:
某个函数需要在每个小时的 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()
来源:https://blog.csdn.net/u010649766/article/details/79446798
标签:Python,执行
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Asp Response.Expires 属性介绍
2008-02-19 17:02:00
python抽象基类用法实例分析
2021-03-04 11:06:25
15个梦幻的登录页面设计展示
2009-07-19 14:17:00
![](https://img.aspxhome.com/file/UploadPic/20097/19/battlenet-37s.jpg)
Python 2/3下处理cjk编码的zip文件的方法
2022-08-05 17:53:40
学习ASP.NET八天入门:第八天
2007-08-07 13:55:00
PHP实现判断二叉树是否对称的方法
2023-06-28 13:24:10
[翻译]标记语言和样式手册 Chapter 11 打印样式
2008-02-11 18:44:00
![](https://img.aspxhome.com/file/UploadPic/20082/11/2008211185712733s.jpg)
python Tensor和Array对比分析
2023-08-27 04:37:02
如何做迅雷电影提示效果
2011-03-31 17:15:00
CSS滤镜示范(filter)附源代码(静态滤镜)
2008-05-18 12:42:00
python实现单张图像拼接与批量图片拼接
2023-07-28 12:33:36
![](https://img.aspxhome.com/file/2023/0/59300_0s.jpg)
SQL Server可写脚本和编程扩展SSIS包
2009-01-20 16:29:00
python编程的核心知识点总结
2023-09-26 21:24:24
python 字典常用方法超详细梳理总结
2023-06-29 05:48:40
排序的人文魅力
2008-05-06 12:47:00
django 邮件发送模块smtp使用详解
2021-09-24 23:04:15
Python+PyQT5的子线程更新UI界面的实例
2022-06-09 10:39:02
如何利用python正确地为图像添加高斯噪声
2023-08-03 08:26:22
![](https://img.aspxhome.com/file/2023/9/59459_0s.png)
Python MD5加密实例详解
2021-10-24 20:31:26
![](https://img.aspxhome.com/file/2023/8/78808_0s.jpg)
sql server 获取系统时间的方法
2023-07-17 07:05:36