scheduler saves tasks to database

This commit is contained in:
iou1name 2020-01-14 07:51:50 -05:00
parent ba683bcdf6
commit 9e46e6d64f

View File

@ -12,10 +12,14 @@ class Scheduler:
self.bot = bot self.bot = bot
self.tasks = [] self.tasks = []
self.lock = threading.Lock() self.lock = threading.Lock()
self.init_database()
self.load_database()
self._t = threading.Thread(target=self.loop) self._t = threading.Thread(target=self.loop)
self._t.start() self._t.start()
def loop(self): def loop(self):
while not self.bot.stillConnected():
time.sleep(1)
while True: while True:
self.lock.acquire() self.lock.acquire()
tasks_due = [t for t in self.tasks if t[1] <= datetime.now()] tasks_due = [t for t in self.tasks if t[1] <= datetime.now()]
@ -24,6 +28,9 @@ class Scheduler:
t = threading.Thread(target=task[0], args=args) t = threading.Thread(target=task[0], args=args)
t.start() t.start()
self.tasks.remove(task) self.tasks.remove(task)
self.bot.db.execute(
"DELETE FROM scheduled_task WHERE dt = ?",
(pickle.dumps(task[1]),))
self.lock.release() self.lock.release()
time.sleep(5) time.sleep(5)
@ -37,7 +44,19 @@ class Scheduler:
self.lock.acquire() self.lock.acquire()
self.tasks.append((func, dt, args)) self.tasks.append((func, dt, args))
self.lock.release() self.lock.release()
# db
def add_periodic_task(self): t = tuple(pickle.dumps(i) for i in (func, dt, args))
pass self.bot.db.execute("INSERT INTO scheduled_task VALUES (?,?,?)", t)
def init_database(self):
self.bot.db.execute("CREATE TABLE IF NOT EXISTS scheduled_task ("
"func BLOB,"
"dt BLOB,"
"args BLOB"
")")
def load_database(self):
tasks = self.bot.db.execute("SELECT * FROM scheduled_task").fetchall()
for task in tasks:
t = tuple(pickle.loads(i) for i in task)
self.tasks.append(t)