Scheduling Cron Jobs in Python Using FastAPI

Posted by

Cron Jobs in Python | Schedule Jobs in Python | FastAPI

Cron Jobs in Python | Schedule Jobs in Python | FastAPI

Cron jobs are a time-based scheduling system in Unix-like operating systems. In Python, you can use the
schedule library to schedule jobs and the FastAPI framework to create APIs that trigger
these jobs.

Using the schedule Library

The schedule library allows you to schedule jobs to run at specific times or intervals using a
fluent API. Here’s a simple example of scheduling a job to run every day at 3:00 PM:

import schedule
import time

def job():
    print("Running job...")

schedule.every().day.at("15:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
    

Using the schedule library, you can create more complex schedules, such as running a job every
weekday at a specific time, or running a job every 30 minutes.

FastAPI Integration

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python. You can
integrate the schedule library with FastAPI to create an endpoint that triggers a job.
Here’s an example of how you can do that:

from fastapi import FastAPI, BackgroundTasks
import schedule
import time
import threading

app = FastAPI()

def job():
    print("Running job...")

def run_schedule():
    while True:
        schedule.run_pending()
        time.sleep(1)

schedule.every().day.at("15:00").do(job)

@app.get("/trigger-job")
async def trigger_job(background_tasks: BackgroundTasks):
    background_tasks.add_task(job)

if __name__ == "__main__":
    t = threading.Thread(target=run_schedule)
    t.start()
    uvicorn.run(app, host="0.0.0.0", port=8000)
    

In this example, we define a job function that prints “Running job…”, and then we schedule it to run at 3:00 PM
every day. We then define a trigger_job endpoint that triggers the job using BackgroundTasks.

Conclusion

Cron jobs and scheduling jobs in Python with the schedule library and FastAPI can be
incredibly powerful tools for automating tasks and creating resilient and responsive APIs. Whether it’s
triggering a daily data backup or running a complex ETL process, these tools enable you to create sophisticated
scheduled job systems using Python.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@padmanabh7031
6 months ago

Thanks for the video! Would really appreciate the Github Link to the code.

@deensdevsasmr4422
6 months ago

Thanks for the video, simple and clear explanation👏