为什么下面 docker 里面的 cron 定时任务没起作用

2022-10-24 17:29:57 +08:00
 proxytoworld

我在 docker 里面起了两个定时任务 /var/spool/cron/crontabs/root

* * * * * python3 /reminder/webhook/main.py
*   * * * * echo "1" >> /reminder/webhook/1.txt

文件权限如下

root@c565c6a20cba:/reminder/webhook# ls -la
total 36
drwxr-xr-x 4 root root 4096 Oct 24 09:19 .
drwxr-xr-x 3 root root 4096 Oct 24 08:19 ..
-rw-r--r-- 1 root root   22 Oct 24 09:29 1.txt
drwxr-xr-x 2 root root 4096 Oct 24 08:22 __pycache__
-rw-r--r-- 1 root root  434 Oct 24 08:19 configs.py
drwxr-xr-x 2 root root 4096 Oct 24 08:19 data
-rw-r--r-- 1 root root 1329 Oct 24 08:19 main.py
-rw-r--r-- 1 root root 2866 Oct 24 08:19 monitor.py
-rwxr--r-- 1 root root   16 Oct 24 08:23 run.sh

为什么第一个定时任务不起作用呢

1219 次点击
所在节点    问与答
13 条回复
goodryb
2022-10-24 17:41:31 +08:00
盲猜 python3 路径的问题,如果正确安装了 python3 ,定时任务里面可以指定绝对路径试试
* * * * * /usr/bin/python3 /reminder/webhook/main.py

或者可能是你的 main.py 有问题
fantasticlw
2022-10-24 17:50:26 +08:00
也许是因为 cron 从非交互式、非登录 shell 运行作业,所以当 cron 执行作业时,它不会从~/.bashrc 、~/.bash_profile 、/etc/profile 等文件加载环境变量。所以对于 cron 不知道 PATH 环境变量,自然不知道 python3 的位置
Vegetable
2022-10-24 18:15:26 +08:00
你就当 cron 没有 PATH ,所以 python 他是找不到的。
ClericPy
2022-10-24 18:39:11 +08:00
cron 启动时候环境变量啥的基本都是空的... 吃过亏,你重定向 stderr 看看就知道了
infun
2022-10-24 18:49:28 +08:00
@goodryb @proxytoworld 就是这个原因,我之前设置定时重启时候发现的,只能这样设置

0 4 * * * /usr/sbin/reboot
oldshensheep
2022-10-24 18:50:34 +08:00
用 cron 定时运行任务我一般这么搞,新建一个 xxx.sh 文件,然后在 xxx.sh 文件开头加上#!/bin/bash ,接着写上要运行的东西。
然后在 cron 加上运行 xxx.sh 的任务。
这样的好处就是和 bash 下的环境一样,而且改运行内容也比较方便。
yangg
2022-10-24 20:12:20 +08:00
cronitor 是个好东西
balabalaguguji
2022-10-24 20:23:14 +08:00
cron 是个服务,你要启动它
liuzhaowei55
2022-10-24 21:02:12 +08:00
1. cron 前台运行,不能后台运行
2. 程序路径使用绝对路径定义

之前折腾的时候遇到过类似问题
ungrown
2022-10-24 23:44:02 +08:00
@fantasticlw #2 自信点,把也许去掉,就是 PATH 的原因。你回想一下常见发行版 Linux 中的 cron 配置文件,开头部分是不是都在添 PATH ?
proxytoworld
2022-10-25 00:00:13 +08:00
@ungrown 如果设置如下定时任务:
* * * * * /path/to/shell/script

在脚本里面
#!/bin/bash
python3 main.py 也不可以吗
proxytoworld
2022-10-25 00:00:32 +08:00
@balabalaguguji 起了 service cron start
ungrown
2022-10-25 00:27:36 +08:00
@proxytoworld #11 可以的呀,你都指定绝对路径了,PATH 缺了也无所谓了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/889457

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX