我已安装的应用程序中有"django_crontab"。
我配置了一个 cron 作业
CRONJOBS = [
('* * * * *', 'django.core.management.call_command',['dbbackup']),
]
我的 YAML 看起来像这样:
web:
build: .
command:
- /bin/bash
- -c
- |
python manage.py migrate
python manage.py crontab add
python manage.py runserver 0.0.0.0:8000
构建 + 然后我打开 CLI:
$ python manage.py crontab show
Currently active jobs in crontab:
efa8dfc6d4b0cf6963932a5dc3726b23 -> ('* * * * *', 'django.core.management.call_command', ['dbbackup'])
然后我尝试:
$ python manage.py crontab run efa8dfc6d4b0cf6963932a5dc3726b23
Backing Up Database: postgres
Writing file to default-858b61d9ccb6-2021-07-05-084119.psql
一切都很好,但 cronjob 永远不会被执行。我没有按预期每分钟看到新的数据库转储。
django-crontab
本身并不运行计划作业; 它只是系统 cron 守护进程的包装器(例如,您需要使用crontab(1) 的位置来配置它)。 由于 Docker 容器只运行一个进程,因此您需要第二个容器来运行 cron 守护程序。
我在这里可能建议的设置是编写一些其他脚本来执行所有必需的启动时设置,然后运行一些可以作为附加参数传递的命令:
#!/bin/sh
# entrypoint.sh: runs as the main container process
# Gets passed the container's command as arguments
# Run database migrations. (Should be safe, if inefficient, to run
# multiple times concurrently.)
python manage.py migrate
# Set up scheduled jobs, if this is the cron container.
python manage.py crontab add
# Run whatever command we got passed.
exec "$@"
然后在您的 Dockerfile 中,将此脚本设为ENTRYPOINT
。 确保也提供默认CMD
,可能是运行主服务器的内容。 在提供两者的情况下,Docker会将CMD
作为参数传递给ENTRYPOINT
。
# You probably already have a line like
# COPY . .
# which includes entrypoint.sh; it must be marked executable too
ENTRYPOINT ["./entrypoint.sh"] # must be JSON-array form
CMD python manage.py runserver 0.0.0.0:8000
现在,在docker-compose.yml
文件中,您可以从同一映像提供两个容器,但只能覆盖 cron 容器的command:
。 入口点脚本将针对两者运行,但在其最后一行启动不同的命令。
version: '3.8'
services:
web:
build: .
ports:
- '8000:8000'
# use the Dockerfile CMD, don't need a command: override
cron:
build: .
command: crond -n # for Vixie cron; BusyBox uses "crond -f"
# no ports: