Maxime Guilbert
Posted on November 16, 2021
In some projects, we need to do dome recurrent tasks while running a Flask API.
So do be able to do it in a Flask project, we need to use APScheduler.
With this tool, we are able to create background schedulers which will execute our recurrent task.
Install
Using pip, you can install the library as follow.
pip install APScheduler
Usage
To use it, check the following example.
import time
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
# Declaration of the task as a function.
def print_date_time():
print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))
# Create the background scheduler
scheduler = BackgroundScheduler()
# Create the job
scheduler.add_job(func=print_date_time, trigger="interval", seconds=3)
# Start the scheduler
scheduler.start()
# /!\ IMPORTANT /!\ : Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
Links
- APScheduler library : https://pypi.org/project/APScheduler/
I hope it will help you! πΊ
π πͺ π
π©
Maxime Guilbert
Posted on November 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.