Nowadays, scheduled actions have always been a debating topic amongst passionate python developers. Some people are convinced that celery or cronjob is the best in creating scheduled jobs. However, I advocate the idea that repeated tasks in FastAPI or Flask are more suitable for API services.
Cronjob 's Ubuntu system is a solution I got exposed to at first. It gives you a simple setting with commands and people can get lots of tutorials in the community. However, If developers want a stable process or track details, cronjob is not a good option. Let's go to terminal.
0 0 * * * is time which cronjob run. Developers can check syntax scheduled time on website crontab.guru
Now, I introduce other solutions for this problem which i have tried. They totally replace cronjob.
On the one hand, Celery is an effective procedure for scheduled tasks. Firstly, It is a long-standing process. To clarify, celery is a large library integrated with many frameworks such as django. So, it has been certificated by the community in the long time. Secondly, there are lots of functions such as logger, task, and consumption in micro services. Nevertheless, there must be another process to run celery. It means developers have two processes, one for website api and one for celery. For example.
Configure Celery to use the django-celery-results backend.
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
On the other hand, from my personal perspective, I would completely convinced that Repeated tasks in FasiAPI or Flask get more benefit than others. First and foremost, It is easy to config and deep understand. In fact, people can figure out how it really works in framework documents. Furthermore, there are no other processes like the former approach. Service api and repeated tasks can run in the sole process due to they are effected by async in python language. However, it can not solve complicated problems.
There is a simple example in FastAPI.
from fastapi import FastAPI
from fastapi_utils.tasks import repeat_every
app = FastAPI()
@app.on_event("startup")
@repeat_every(seconds=60 * 60) # 1 hour
def remove_expired_tokens_task() -> None:
# Do some thing ...
In conclusion, It is my view that Repeated Tasks in FastAPI or Flask have priority over crontab and celery because of convenience and performance.