定时任务
##最简单版本,直接使用crontab -e修改里面的定时任务
* * * * * sh /root/start.sh
当你想要使用脚本对定时任务进行添加时
#使用脚本对crontab任务进行添加
##方法1,编辑 /var/spool/cron/用户名 ,简单但是需要该用户名下的权限 例如:
echo "* * * * * sh /root/start.sh" >> /var/spool/cron/root
##方法2,编辑 /etc/crontab 文件,需要用户名的权限,下面例子是'root'的权限:
echo "* * * * * root sh /root/start.sh" >> /etc/crontab
##方法3,使用crontab -l命令和crontab file两个命令实现
crontab -l > conf && echo "* * * * * sh /root/start.sh" >> conf && crontab conf && rm -f conf
crontab的启动等命令
安装:apt-get install cron
启动:service cron start
重启:service cron restart
停止:service cron stop
检查状态:service cron status
查询:cron可用的命令:service cron
检查:Cronta工具是否安装:crontab -l
脚本无法执行问题
如果我们使用 crontab 来定时执行脚本,无法执行,但是如果直接通过命令(如:./test.sh)又可以正常执行,这主要是因为无法读取环境变量的原因。
解决方法:
-
1、所有命令需要写成绝对路径形式,如: /usr/local/bin/docker。
-
2、在 shell 脚本开头使用以下代码:
#!/bin/sh . /etc/profile . ~/.bash_profile
3、在 /etc/crontab 中添加环境变量,在可执行命令之前添加命令 . /etc/profile;/bin/sh,使得环境变量生效,例如:
20 03 * * * . /etc/profile;/bin/sh /var/www/runoob/test.sh