python装饰器实现周期性函数调用
Posted gj4990
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python装饰器实现周期性函数调用相关的知识,希望对你有一定的参考价值。
python的装饰器可用于权限校验,周期性函数调用等功能,下面通过两种方式实现周期性函数的调用。
# -*- coding:utf-8 -*-
from functools import wraps
import time
import datetime
_ts = lambda: time.time()
# 通过__call__实现装饰器类
class PeriodLoopingCall:
def __init__(self, period=60, max_count=0):
self.period = period
self.count = max_count
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
while self.count > 0:
start_time = _ts()
func(*args, **kwargs)
self.count -= 1
end_time = _ts()
delay = end_time - start_time - self.period
time.sleep(-delay if delay < 0 else 0)
return wrapper
# 通过闭包实现装饰器函数
# 由于使用了nonlocal,需要在python 3环境下运行
def period_exec_func(period=60, max_count=0):
def decorator(func):
#使用functools.wraps函数防止原始函数的属性被装饰器函数的属性替换。
#即防止这里的print_info函数属性被wrapper函数属性替换。
count = 0
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal count
while count < max_count:
start_time = _ts()
func(*args, **kwargs)
count += 1
end_time = _ts()
delay = end_time - start_time - period
time.sleep(-delay if delay < 0 else 0)
return wrapper
return decorator
@period_exec_func(period=2, max_count=3)
def print_info1(info):
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
info = "%s %s" %(date, info)
print(info)
@PeriodLoopingCall(period=2, max_count=3)
def print_info2(info):
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
info = "%s %s" %(date, info)
print(info)
def main():
info1 = "This is period decorator function test"
print_info1(info1)
print("*"*60)
info2 = "This is period decorator class test"
print_info2(info2)
if __name__ == "__main__":
main()
运行结果:
2019-10-20 11:09:48 This is period decorator function test
2019-10-20 11:09:50 This is period decorator function test
2019-10-20 11:09:52 This is period decorator function test
************************************************************
2019-10-20 11:09:54 This is period decorator class test
2019-10-20 11:09:56 This is period decorator class test
2019-10-20 11:09:58 This is period decorator class test
以上是关于python装饰器实现周期性函数调用的主要内容,如果未能解决你的问题,请参考以下文章