From 7a17e500692832cadbd41cf3a16a22b9af6f7096 Mon Sep 17 00:00:00 2001 From: iou1name Date: Mon, 13 Jan 2020 12:54:11 -0500 Subject: [PATCH] added scheduler --- bot.py | 4 ++++ scheduler.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 scheduler.py diff --git a/bot.py b/bot.py index ae9d439..4249acb 100755 --- a/bot.py +++ b/bot.py @@ -16,6 +16,7 @@ import db import tools import config import loader +import scheduler from trigger import Trigger class Fulvia(irc.IRCClient): @@ -97,6 +98,9 @@ class Fulvia(irc.IRCClient): self._disabled_modules = config.disabled_modules """These modules will NOT be loaded when load_modules() is called.""" + self.scheduler = scheduler.Scheduler(self) + """The bot's task scheduler.""" + self.load_modules() diff --git a/scheduler.py b/scheduler.py new file mode 100644 index 0000000..c9b7ccd --- /dev/null +++ b/scheduler.py @@ -0,0 +1,43 @@ +#!/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