crontabs 定时任务 sudo错误 及 常用命令

centos 7

1、安装 crontabs服务并设置开机自启:

yum install crontabs
systemctl enable crond
systemctl start crond

2、配置定时规则

vim /etc/crontab

在配置文件中配置你的定时执行规则
每4小时0分钟,执行

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

0 */4 * * * root /home/pm2Restart.sh
每隔30分钟root执行一次pm2Restart.sh
*/30 * * * * root pm2Restart.sh

*  */2  *  *  *root pm2Restart.sh   每2小时执行一次。*之间有空格

每天早上5点定时重启系统:
0 5 * * * root reboot


 * :表示任意的时刻;如小时位 * 则表示每个小时
 n :表示特定的时刻;如小时位 5 就表示5时
 n,m :表示特定的几个时刻;如小时位 1,10 就表示1时和10时
 n-m :表示一个时间段;如小时位 1-5 就表示1到5点
 */n : 表示每隔多少个时间单位执行一次;如小时位 */1 就表示每隔1个小时执行一次命令,也可以写成 1-23/1

pm2Restart.sh

#!/bin/bash
sudo pm2 restart all
exit 1

3、保存生效

crontab /etc/crontab

4、查看任务

crontab -l

到此定时任务配置完成。

问题

crontab运行shell脚本报sudo错误

sudo:sorry, you must have a tty to run sudo.

解决crontab问题:

sudo vim /etc/sudoers

注释掉: Defaults requiretty 或者 Defaults  !visiblepw

因为sudo默认需要tty终端,而crontab里的命令实际是以无tty形式执行的。注释掉"Defaults requiretty"即允许以无终端方式执行sudo

重启服务

service crond restart

crontab服务启动与关闭:

systemctl start crond              //启动服务
systemctl stop crond              //关闭服务
systemctl restart crond          //重启服务
systemctl reload crond          //重新载入配置
systemctl status crond          //cron 状态

你可能感兴趣的:(CentOS)