How to create scheduled jobs in flask using APScheduler.

Khaled Elabady
2 min readMar 1, 2023

--

what is scheduled jobs ?

execute recurring tasks at fixed times (e.g. every minute, every hour, every day at 3pm, …..).

To create scheduled jobs in Flask using APScheduler, you can follow these steps:

  1. Install APScheduler:
pip install apscheduler

2. Import the classes and functions from APScheduler :

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

3. Create an instance of the scheduler:

scheduler = BackgroundScheduler()

4. Define the job function that you want to schedule. For example:

def job():
print("Scheduled job executed")

5. Use the add_job() method of the scheduler to add the job function to the scheduler and schedule it to run at a specific interval. For example:

scheduler.add_job(job, 'interval', hours=2)

you can use the minutes or seconds argument instead of the hours argument.

This will schedule the job to run every 2 hours

Alternatively, you can also use the cron scheduling option to specify more complex scheduling patterns. For example, to schedule a job to run every day at 2 PM, you can use:

scheduler.add_job(job, 'cron', hour=14)

#hour=14 means" 2 PM "

This will schedule the job to run every day at 2 PM. You can also specify additional parameters like minutes, seconds, and days of the week to further customize the scheduling pattern.

6. Start the scheduler when the Flask app starts:

@app.before_first_request
def start_scheduler():
scheduler.start()

This will start the scheduler when the Flask app starts for the first time.

7. stop the scheduler when the Flask app stops:

@app.teardown_appcontext
def stop_scheduler(exception=None):
scheduler.shutdown()

8. Test a scheduled Functions that runs every 30 seconds

Done , every 30 seconds it will print Date Time.

--

--