Oct-15-2022, 10:21 PM
After playing with this a bit, I don't think datetime is the best way to save a datetime object. Following my advice that save values in their most useful format, I wrote an example that saves time as a timestamp. The scheduler uses timestamps. The databases can store timestamps, but DateTime objects have to be converted to and from strings. And using DateTime forces two applications (the one that saves the events and the one that sends the events) to agree on DateTime format used.
This example writes reminders to a database, retrieves them from the database, schedules the reminders, and sends the reminders. The main change needed to make this work with your code is that your events are entered using a datetime string. You'll need to convert that to a datetime object, and then use the datetime object to get a timestamp.
This example writes reminders to a database, retrieves them from the database, schedules the reminders, and sends the reminders. The main change needed to make this work with your code is that your events are entered using a datetime string. You'll need to convert that to a datetime object, and then use the datetime object to get a timestamp.
import sqlite3 as sql from datetime import datetime import sched, time time_format = "%I:%M:%S %p" def send_reminder(sched_time, message): """Just pring the message and the scheduled time (and current time)""" print(message) print(datetime.now().strftime(time_format)) print(datetime.fromtimestamp(sched_time).strftime(time_format)) def save_reminders(reminders): """Make a table in the database to hold the reminders""" now = int(time.time()) db = sql.connect("test.db") db.execute("CREATE TABLE IF NOT EXISTS reminders(message TEXT, time INTEGER)") db.execute("DELETE FROM reminders") for reminder, seconds in reminders: db.execute( "INSERT INTO reminders (message, time) VALUES(?, ?)", (reminder, now + seconds)) db.commit() db.close() def schedule_reminders(schedule): """Get reminders from the database and add to the schedule.""" db = sql.connect("test.db") for reminder in db.execute("SELECT * FROM reminders"): message, sched_time = reminder schedule.enterabs(sched_time, 1, send_reminder, (sched_time, message)) db.close() # Make a database of reminders that run 5, 10 and 15 seconds from now. save_reminders(( ("This is the first message", 5), ("This message is 5 seconds after the first", 10), ("This message is 15 seconds after the first", 20)) ) schedule = sched.scheduler(time.time) schedule_reminders(schedule) while not schedule.empty(): schedule.run()