在Django中,可以使用celery来实现动态添加定时任务。
首先,需要安装Celery:
pip install celery然后,在Django的settings.py文件中配置Celery:
# settings.py# Celery配置CELERY_BROKER_URL = 'redis://localhost:6379/0'CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'CELERY_ACCEPT_CONTENT = ['json']CELERY_TASK_SERIALIZER = 'json'CELERY_RESULT_SERIALIZER = 'json'CELERY_TIMEZONE = 'Asia/Shanghai'接下来,创建一个tasks.py文件,定义定时任务:
# tasks.pyfrom celery import shared_task@shared_taskdef my_task():# 定时任务要执行的操作pass然后,在视图函数或其他地方动态添加定时任务:
from tasks import my_taskfrom datetime import datetime, timedeltafrom celery.schedules import crontabfrom celery.task import periodic_task@periodic_task(run_every=crontab(minute='*/1'))def add_task():now = datetime.now() + timedelta(minutes=1)my_task.apply_async(eta=now)在上面的例子中,每分钟动态添加一个定时任务,任务的具体操作在my_task函数中定义。
最后,启动Celery的worker和beat:
celery -A your_project_name worker -l infocelery -A your_project_name beat -l info这样就可以动态添加定时任务了。

