Linux篇1----crontab

问题:

手动输入:

/bin/sh /mnt/test1.sh

可以执行,但放在crontab里就总是不起作用。(centos7.9)

一、编辑新的定时任务

crontab -e

 分 时 日 月 周

校验 https://tool.lu/crontab

如果出现 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 否则会找不到一些第三方库

参考文章:http://t.zoukankan.com/mysticbinary-p-13371189.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值