问题:
手动输入:
/bin/sh /mnt/test1.sh
可以执行,但放在crontab里就总是不起作用。(centos7.9)
一、编辑新的定时任务
crontab -e
分 时 日 月 周
如果出现 installing 代表成功
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
27 19 * * 1-5 . /etc/profile;/bin/sh /opt/test.sh
*/1 * * * * . /etc/profile;touch /opt/001.txt
查看状态与重启
service crond status
service crond restart
查看日志
tail -f /var/log/cron
二、环境变量
Q:手动执行脚本可运行,定时任务时,则无反应
A:主要的问题来源于crontab本身,因为在我们执行的脚本中,会涉及到一些环境变量,当手动执行时,实在shell环境中进行,脚本会自动查找环境变量。而当使用任务调度时,由于crontab本身是不会加载变量,因此就会导致运行失败。
解决方案:
* * * * * ./etc/profile; mycommand
OR
* * * * * . ~/.bash_profile; mycommand
1
2
3
看你环境变量究竟在哪写着
两者区别:
前者是系统整体的设置,后者是个人设置。下面绝对路径是go语言的二进制执行文件即可
三、最终结果
[root@iZuf65kcvwmcx6qb9t8qg3Z ~]# crontab -uroot -l
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
51 19 * * 1-5 . /etc/profile;/bin/sh /opt/testdata/gotest/test.sh
10 15 * * 1-5 . /etc/profile;/opt/testdata/gotest/main
30 15 * * 1-5 . /etc/profile;/opt/testdata/gotestshanghai/main
*/2 * * * * . /etc/profile;touch /opt/testdata/gotest/001.txt
## 9:30到10点可以这样crontab
30-59/1 9 * * 1-5 . /etc/profile;python /mnt/ay.py
四、定时任务启动go语言的程序
10 17 * * 1-5 . /etc/profile;bash /root/test/run.sh >> /root/test/log.txt
#!/bin/sh
cd /opt/project/
go run /opt/project/main.go
要在自己的项目目录结构下如运行main.go 否则会找不到一些第三方库