man-shuo / manshuo-bot

基于Mirai和Manyana发起由个人与朋友维护的qqbot
GNU Affero General Public License v3.0
3 stars 0 forks source link

111 #1

Open cscs666 opened 2 months ago

cscs666 commented 2 months ago

from datetime import datetime import time import random from functools import wraps

1=限定时间内才可能执行函数,2=概率触发函数,3=函数总执行次数限制,4=至少每隔xx秒运行一次函数

timeLimit=[[starttime1,endtime1],[starttime2,endtime2],...],starttime=[年,月,日,时,分,秒]

def functionLimit(timeLim:list=[datetime(1970, 1, 1, 0, 0,0),datetime(2030, 1, 1, 0, 0,0)],probLim:float=1,freqLim:float=1e6,executePerTime:int=0,switch=0): def limiting_decorator(func): freqLimCounter=[0] lastCalltime=[datetime(2024,9,4,16,44,44)] timeLimitPacked=[] for timeLimItem in timeLim: timeLimitPacked.append([datetime(1970, 1, 1, 0, 0,0),datetime(1970, 1, 1, 0, 0,0)]) def inner(*args,kwargs): if switch==0: func(*args,*kwargs) return func elif switch==1: now=datetime.now() flag=0 for timeLimitItem in timeLimitPacked: if timeLimItem[0].timestamp()<=now.timestamp() and timeLimItem[1].timestamp()>=now.timestamp(): flag=1 break if flag==1: func(args,kwargs) return func elif switch==2: if random.random()<probLim: func(*args,kwargs) return func elif switch==3: freqLimCounter[0]+=1 print("函数已经调用",freqLimCounter[0],"次") if freqLimCounter<=freqLim: func(*args,*kwargs) return func elif switch==4: now=datetime.datetime.now() if now.timestamp()-lastCalltime[0].timestamp()>executePerTime: lastCalltime[0]=now func(args,kwargs) return func else: print("input error") raise ValueError return inner return limiting_decorator

@functionLimit(switch=1,timeLim=[[datetime(2024,9,4,17,45,44),datetime(2024,9,4,17,47,00)]]) def func1(info1,info2): print(info1+info2)

@functionLimit(switch=2,probLim=0.5) def func2(info1,info2): print(info1+info2)

@functionLimit(switch=3,freqLim=10) def func3(info1,info2): print(info1+info2)

@functionLimit(switch=4,executePerTime=2) def func4(info1,info2): print(info1+info2)

def test1(): while(1): func1(1,2) print(datetime.now().ctime) time.sleep(1) def test2(): while(1): func2(1,2) print(datetime.now().ctime) time.sleep(1) def test3(): while(1): func3(1,2) print(datetime.now().ctime) time.sleep(1) def test4(): while(1): func4(1,2) print(datetime.now().ctime) time.sleep(1)

test2()

man-shuo commented 2 months ago

thank you for your issue