Automate a Task with Ofelia Cron in Docker and FastAPI

Tiempo de lectura: < 1 minuto

Reading Time: 1 minute

Hello, today we are going to learn how to automate a task using Ofelia, FastAPI, and SQLAlchemy.

The first thing we are going to do is create the file that we want to execute with Ofelia’s Cron:

cron_execute.py

# Create or get db_session
from crud.operations_crud import operacion_crud_generar_estadisticas
from config.connection import get_db

db_session = next(get_db())

print("Executing")

operacion_crud_generar_estadisticas(db_session=db_session)

print("End")

First, we import the CRUD operation that will execute the task in the database.

Then, we import the connection created by FastAPI as a session.

This way, we can reuse the structured code in FastAPI and avoid duplicating it.

It is important that this file is in the root of the project app/cron_execute.py, as we will run it as if it were a module with Python.

python -m cron_execute

Once created, we will install Ofelia with Docker Compose. For this, we can check this POST: https://devcodelight.com/automatizar-tareas-con-cron-desde-docker-con-ofelia/

Our Ofelia configuration file config.ini will be as we like:

[job-exec "job-executed-on-running-container"]
schedule =  @daily
container = fast_api_container
command = python -m cron_execute

schedule = @daily -> It indicates that it will run once a day.

container = fast_api_container -> It indicates the name of the container.

command = python -m cron_execute -> It indicates the command to be executed inside the container.

Comments will appear in the Ofelia container.

*Note: Every time we change the config.ini, if we have Ofelia running, we must restart the container to refresh the changes.

Leave a Comment