容器中运行定时任务
容器中运行定时任务
背景
- 想使用Docker容器中跑一个定时任务,于是有了本篇文章
思路
- 经过查询,有的帖子建议使用宿主机执行定时的
docker exec
命令,但是这样感觉使用Docker的意义就不大了,还是把定时任务放在容器中比较好 - 因此直接在容器中使用
cron
执行定时任务,但是这其中的坑比较多,特此记录
操作
-
submit.sh 要定时执行的脚本
#!/bin/bash echo "$(date): " >> /var/log/cron.log 2>&1 /usr/local/bin/python /usr/src/app/submit_3chk.py >> /var/log/cron.log 2>&1
- 注意在定时执行的脚本中的命令要使用绝对值指定可执行文件的位置
-
cronfile 定时任务配置文件
13 8 * * * root /usr/src/app/submit.sh
- cron时间格式这里不再赘述
- 每天的8:13使用root用户执行submit.sh脚本
-
Dockerfile
FROM python:3 WORKDIR /usr/src/app # 安装依赖 COPY . . RUN pip install --no-cache-dir -r requirements.txt # Install Pip RUN apt update RUN apt install -y cron # 设置定时脚本权限 RUN chmod +x submit.sh # Add crontab file in the cron directory ADD cronfile /etc/cron.d/submit-cron # Give execution rights on the cron job RUN chmod 0644 /etc/cron.d/submit-cron # Create the log file to be able to run tail RUN touch /var/log/cron.log # 更改时区 RUN rm -rf /etc/localtime RUN ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime # Run the command on container startup CMD cron && tail -f /var/log/cron.log
- 核心步骤:
- 定时脚本要加可执行权限
- 定时配置文件放到
/etc/cron.d/
目录下 - 更改时区为
Asia/Shanghai
- 执行
cron
- 核心步骤:
-
构建镜像后运行容器即可
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通