scheduler saves tasks to database
This commit is contained in:
parent
ba683bcdf6
commit
9e46e6d64f
25
scheduler.py
25
scheduler.py
|
@ -12,10 +12,14 @@ class Scheduler:
|
|||
self.bot = bot
|
||||
self.tasks = []
|
||||
self.lock = threading.Lock()
|
||||
self.init_database()
|
||||
self.load_database()
|
||||
self._t = threading.Thread(target=self.loop)
|
||||
self._t.start()
|
||||
|
||||
def loop(self):
|
||||
while not self.bot.stillConnected():
|
||||
time.sleep(1)
|
||||
while True:
|
||||
self.lock.acquire()
|
||||
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.start()
|
||||
self.tasks.remove(task)
|
||||
self.bot.db.execute(
|
||||
"DELETE FROM scheduled_task WHERE dt = ?",
|
||||
(pickle.dumps(task[1]),))
|
||||
self.lock.release()
|
||||
time.sleep(5)
|
||||
|
||||
|
@ -37,7 +44,19 @@ class Scheduler:
|
|||
self.lock.acquire()
|
||||
self.tasks.append((func, dt, args))
|
||||
self.lock.release()
|
||||
# db
|
||||
|
||||
def add_periodic_task(self):
|
||||
pass
|
||||
t = tuple(pickle.dumps(i) for i in (func, dt, args))
|
||||
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)
|
||||
|
|
Loading…
Reference in New Issue
Block a user