# systemctl status crond
说明:和其他service的执行相同:
启动: systemctl start crond
停止: systemctl stop crond
说明:crond服务一般linux系统会默认安装,
如果不存在,可以用这个命令安装:
# yum install crontabs
默认位于/var/log目录下,cron打头
# ll /var/log/cron*
-rw------- 1 root root 35831 Mar 6 14:01 /var/log/cron
-rw------- 1 root root 45705 Feb 9 03:01 /var/log/cron-20200209
-rw------- 1 root root 45596 Feb 16 03:01 /var/log/cron-20200216
-rw------- 1 root root 45227 Feb 23 03:01 /var/log/cron-20200223
-rw------- 1 root root 45429 Mar 1 03:01 /var/log/cron-20200301
1,编辑配置
# crontab -e
2,查看已添加的定时任务:
# crontab -l
位于 /var/spool/cron这个目录下,
如果用root账户配置了定时任务,则可以看到有一个root文件:
# ls /var/spool/cron/
root webop
# more /var/spool/cron/root
此处即为我们所添加的定时任务
查看/etc/crontab文件可以看到crontab所定义的命令格式:
# more /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# 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
说明:5个*分别代表:
1. 分钟
2. 小时
3. 天
4. 月
5. 周几
1,每天的0点0分,执行一个切分日志的脚本程序
0 0 * * * sh /data/web/cmd/split_log_shell/splitlog.sh >> /data/logs/cronlogs/splitlog.log <span class="token file-descriptor important">2></span>&1
2,每15分钟,执行一个检查php日志中是否出现报错的程序
*/15 * * * * /data/software/php7/bin/php /data/web/cmd/check_php_error/check_error_for_php_log.php >> /data/logs/cronlogs/checkphperror.log <span class="token file-descriptor important">2></span>&1
3,在指定的分钟,运行一个导出数据的脚本
0,15,30,45 * * * * sh /usr/sbin/backupMysql.sh >> /data/logs/cronlogs/backupmysql.log <span class="token file-descriptor important">2></span>&1
说明: 2>&1的作用:把shell的错误输出2也转为输出到正常输出1,
否则如果程序运行出错时,错误信息不会被记录到命令行上所添加的日志文件中
应该有一个保存cron输出内容的日志目录,
用来记录下crond运行时的情况,
把数据输出到这里
crond自身的日志只记录了在相应的时间程序是否有执行,没有执行情况的反馈
创建cron的日志目录
# mkdir /data/logs/cronlogs
# chmod 777 /data/logs/cronlogs/
$ crontab -V
cronie 1.5.2
$ crond -V
cronie 1.5.2
说明:用crontab crond两个命令均可
因为它们属于同一个安装包
用下面的命令可以查看:
$ rpm -ql cronie
$ cat /etc/redhat-release
CentOS Linux release 8.4.2105
chmod +x demo-crond.sh
也可以直接在 /etc/crontab 中添加任务
vim /etc/crontab
比如添加如下任务, 每5分钟执行一次
*/5 * * * * root bash /root/demo-crond.sh
https://www.cnblogs.com/architectforest/p/12435344.html
实际例子:
# git_pull.sh 文件内容
cd /root/web/antword
git pull >> /root/web/antword/git_pull_log.txt
# end
chmod +x git_pull.sh
vi git_pull_log.txt
chmod 777 git_pull_log.txt
bash git_pull.sh
systemctl restart crond.service
ll /var/log/cron*
systemctl status crond.service
cd ..
/bin/bash /root/web/antword/git_pull.sh
crontab -e
# 内容如下
*/1 * * * * sh /root/web/antword/git_pull.sh
*/1 * * * * sleep 20 && sh /root/web/antword/git_pull.sh
*/1 * * * * sleep 40 && sh /root/web/antword/git_pull.sh
# end
systemctl restart crond.service
ll /var/log/cron*
vi /var/log/cron-20231210
ll /var/log/cron*
cat git_pull_log.txt