APScheduler
Cron jobs are a way to schedule tasks to run at specific times or intervals. A cron expression is a string consisting of five or six fields that represent different time units (minute, hour, day of the month, month, day of the week). For example, the cron expression 0 0 * * *
means the task will run at midnight (00:00) every day.
In a FastAPI application, cron jobs can be used for various purposes:
First, make sure you have FastAPI installed. If not, you can install it using pip
:
pip install fastapi uvicorn
We will also use APScheduler
, a powerful and flexible in - memory task scheduler in Python. Install it using:
pip install apscheduler
APScheduler
APScheduler
provides several types of schedulers, but for our FastAPI application, we will use the BackgroundScheduler
. Here is a simple example:
from fastapi import FastAPI
from apscheduler.schedulers.background import BackgroundScheduler
app = FastAPI()
# Function to be scheduled
def job():
print("This is a scheduled task.")
# Create a scheduler
scheduler = BackgroundScheduler()
scheduler.add_job(job, 'interval', minutes=1) # Run the job every minute
scheduler.start()
@app.get("/")
async def root():
return {"message": "FastAPI with scheduled tasks"}
To run the FastAPI application, use the following command:
uvicorn main:app --reload
In this example, we define a simple function job
that will be executed every minute. We create a BackgroundScheduler
, add the job to it, and start the scheduler.
When scheduling tasks, it’s important to handle errors properly. Here is an updated version of the previous example with error handling:
from fastapi import FastAPI
from apscheduler.schedulers.background import BackgroundScheduler
import logging
app = FastAPI()
# Configure logging
logging.basicConfig(level=logging.ERROR)
# Function to be scheduled
def job():
try:
print("This is a scheduled task.")
# Add your actual task logic here
except Exception as e:
logging.error(f"Error in scheduled task: {e}")
scheduler = BackgroundScheduler()
scheduler.add_job(job, 'interval', minutes=1)
scheduler.start()
@app.get("/")
async def root():
return {"message": "FastAPI with scheduled tasks"}
Logging is crucial for monitoring the execution of scheduled tasks. As shown in the above example, we configure basic logging to record any errors that occur during the execution of the scheduled task.
Scheduled tasks should be isolated from the main application logic as much as possible. This means that the scheduled tasks should not rely on the state of the FastAPI application, and vice versa. For example, if your scheduled task needs to access the database, it should establish its own database connection rather than relying on a connection from the main application.
Write unit tests for your scheduled tasks. You can use the unittest
or pytest
frameworks to test the functions that are scheduled. Here is a simple example using pytest
:
import pytest
def job():
return "Task completed"
def test_job():
result = job()
assert result == "Task completed"
Implementing cron jobs in a FastAPI application can be a powerful way to automate various tasks. By using APScheduler
, we can easily schedule tasks at specific intervals or times. We have covered the fundamental concepts, usage methods, common practices, and best practices for implementing cron jobs in FastAPI. Remember to handle errors, use logging, isolate scheduled tasks, and test your code to ensure the reliability and maintainability of your application.