fulvia/scheduler.py

44 lines
1.0 KiB
Python
Raw Normal View History

2020-01-13 12:54:11 -05:00
#!/usr/bin/env python3
"""
Allows the bot to scheduler tasks to be performed later.
"""
import time
import pickle
import threading
from datetime import datetime
class Scheduler:
def __init__(self, bot):
self.bot = bot
self.tasks = []
self.lock = threading.Lock()
self._t = threading.Thread(target=self.loop)
self._t.start()
def loop(self):
while True:
self.lock.acquire()
tasks_due = [t for t in self.tasks if t[1] <= datetime.now()]
for task in tasks_due:
args = (self.bot,) + task[2]
t = threading.Thread(target=task[0], args=args)
t.start()
self.tasks.remove(task)
self.lock.release()
time.sleep(5)
def add_task(self, func, dt, args):
"""
`func` - The function to call. Must accept `bot` as the first
argument. Must be picklable.
`dt` - A datetime object representing when to call the function.
`args` - Arguments to call the function with, not including `bot`.
"""
self.lock.acquire()
self.tasks.append((func, dt, args))
self.lock.release()
# db
def add_periodic_task(self):
pass