dkcht2innanetrlycht/ratelimiter.py

25 lines
806 B
Python
Raw Permalink Normal View History

2022-08-03 03:42:45 +00:00
#naive ratelimiter
from time import time
class ratelimit():
def __init__(self, min_delay):
self.delay = min_delay
self.last_action = 0
self.action_queue = []
2023-10-29 05:52:37 +00:00
def action(self, manual, target, args):
2022-08-03 03:42:45 +00:00
print("action~", target, args)
if time() - self.last_action > self.delay:
self.last_action = time()
target(*args)
2023-10-29 05:52:37 +00:00
try: self.action_queue.remove((target, args))
except: print("did not remove", target, args)
2022-08-03 03:42:45 +00:00
else:
print("deferred")
2023-10-29 05:52:37 +00:00
if manual:
self.action_queue.append((target, args))
2022-08-03 03:42:45 +00:00
def lazyrun(self):
if len(self.action_queue) <= 0: return
f = self.action_queue[0][0]
args = self.action_queue[0][1]
2023-10-29 05:52:37 +00:00
self.action(False, f, args)