How to restore scheduler tasks in Python after restarting in telegram bot?

61 Views Asked by At

I’m writing telegram bot and in some places, for instance, user bought a subscription and after a month scheduler has to turn off it, but after reboot all data from RAM will be deleated and this tasks won’t be finished. I use AsyncIOScheduler. After restarting the code I need to continue all scheduled tasks. I tried it, start scheduler, after I restarted the code added in beginning scheduler.start() to continue scheduler tasks from db, but this doesn’t work.

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler

def f():
    print("Hello, World!")

jobstore = {
"default": SQLAlchemyJobStore(url="sqlite:///scheduler.db")
}

scheduler = AsyncIOScheduler(jobstores=jobstore)

@router.message(CommandStart())
async def start_handler(message: Message):
    scheduler.add_job(f, "date", id="job_1", jobstore="default", run_date=(datetime.datetime.now() + datetime.timedelta(seconds=30)))
    scheduler.start()

What can I do to solve it?

1

There are 1 best solutions below

0
yusuf On

It can be useful to set automatically turn off subscription, for instance, but sometimes it’s necessary to restart your code. I’ve found decision.

from apscheduler.jobstores.sqlalchemy      import SQLAlchemyJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler

def f():
    print("Hello, World!")

scheduler = AsyncIOScheduler(jobstores=jobstore)
scheduler.add_jobstore(“sqlalchemy”, url=“sqlite:///scheduler.db”)
scheduler.start()
@router.message(CommandStart())
async def start_handler(message: Message):
    scheduler.add_job(f, "date", id="job_1", run_date=(datetime.now() + timedelta(seconds=30)), misfire_grace_time=3600)

When you initialise Scheduler object, after it add scheduler.start() to automatically start planned functions. Also add misfire_grace_time argument, for instance, your function has to work on period of time when your code stopped. After reloading it will automatically called even if time has expired