Simplifying Task Scheduling in FastAPI with Cron Jobs

Gopal Katariya
2 min readNov 20, 2024

--

Introduction

  • Briefly introduce FastAPI and its efficiency for modern web applications.
  • Explain what cron jobs are and their significance in automating repetitive tasks.
  • Mention how scheduling tasks can enhance an application’s utility.

Setting Up Your FastAPI Project

  1. Create a FastAPI project if you don’t have one:
pip install fastapi uvicorn

2. Set up a directory structure for your project, e.g., app/.

Adding a Task Scheduler

  • Explain that Python’s APScheduler library is well-suited for handling cron jobs.
  • Install APScheduler :
pip install apscheduler

Integrating APScheduler into FastAPI

  1. Initialize APScheduler: Create a scheduler instance and include it in the FastAPI app:
from fastapi import FastAPI
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import time

app = FastAPI()
scheduler = BackgroundScheduler()

2. Define a Job: Create a sample task:

def print_time():
print(f"The current time is {time.ctime()}")

3. Add a Cron Job: Schedule the task:

scheduler.add_job(print_time, CronTrigger(minute="*/1"))  # Every minute
scheduler.start()

4. Shutdown Handling: Ensure the scheduler stops gracefully:

import atexit

@atexit.register
def shutdown():
scheduler.shutdown()

Running Your Application

  • Start the FastAPI app:
uvicorn app.main:app --reload
  • Demonstrate that the task runs as per the schedule.

Advanced Scheduling Options

  • Discuss other APScheduler triggers (interval, date).
  • Mention persistent job stores for long-term task management.

Conclusion

  • Recap the simplicity of setting up cron jobs in FastAPI.
  • Encourage readers to try it in their projects for task automation.

Feel free to connect:

LinkedIN : https://www.linkedin.com/in/gopalkatariya44/

Github : https://github.com/gopalkatariya44/

Instagram : https://www.instagram.com/_gk_44/

Twitter: https://twitter.com/GopalKatariya44

Youtube: https://youtube.com/@gopalkatariya44

Thanks 😊 !

--

--

Gopal Katariya
Gopal Katariya

Written by Gopal Katariya

AI Engineer | Machine Learning Enthusiast | Transforming Ideas into Intelligent Solutions

No responses yet