Is there a way to add jobs using APScheduler while the app is running on Heroku?

31 Views Asked by At

I'm trying to build a flask app that allows users to schedule tasks to be run at specific times throughout the day. There are lots of tutorials on scheduling tasks with APScheduler on Heroku, however, they all require you to define the task before deploying the app. I would like to be able to call scheduler.add_job() during runtime. Is this possible?

I have tried following https://devcenter.heroku.com/articles/clock-processes-python and creating a clock.py file but this is not what I want because I want to be able to schedule jobs while the app is running and this method does not allow for that.

I had an idea to use MongoDB and create an endpoint in the flask app which stores a new job in the db then in my clock.py I could use MongoDBJobStore to automatically detect the new job but I have no idea how to do that.

Any ideas are appreciated!

1

There are 1 best solutions below

0
user23401828 On

You can call add_job() during runtime as long as the application is running on loop. For example, you are running Flask which should be on loop already.

If you are using Flask and expose API application, you can let users queue task on frontend/POST event. Then on Flask just simple collect and run add_job() with corresponse params.

Better check docs here

Example below is FastAPI snipped code:

@router.post("/queue")
async def queue_task(
    value: Annotated[str | None, Form()] = None
)
    # your code goes here

    # schedule your task here
    scheduler.add_job(
        func=func_name,
#        args=[]
#        kwargs={"key": value},
#        executor="processpool", # need if you want to execute this on other pool, make sure you have setup it first
        # etc. args
    )