CentOS定时任务

概述

crontab命令常见于Unix和类Unix的操作系统之中,用于设置周期性被执行的指令。该命令从标准输入设备读取指令,并将其存放于“crontab”文件中,以供之后读取和执行。该词来源于希腊语 chronos(χρνο),原意是时间。通常,crontab储存的指令被守护进程激活, crond常常在后台运行,每一分钟检查是否有预定的作业需要执行。这类作业一般称为cron jobs。

Linux crontab是用来定期执行程序的命令。
当安装完成操作系统之后,默认便会启动此任务调度命令。
crond 命令每分锺会定期检查是否有要执行的工作,如果有要执行的工作便会自动执行该工作。

crontab使用

1
2
3
4
5
6
7
8
9
10
Options:
-u <user> define user
-e edit user's crontab
-l list user's crontab
-r delete user's crontab
-i prompt before deleting
-n <host> set host in cluster to run users' crontabs
-c get host in cluster to run users' crontabs
-s selinux context
-x <mask> enable debugging
  • 我们使用service crond status命令来查看当前定时服务是否开启

查看定时服务状态

  • 使用crontab -e来创建一个定时任务
    首先我们简单的创建一个shell脚本,输出一个hello world
1
echo "hello world!"
1
vim /etc/crontab

cron写法

1
2
3
4
#然后输入来创建当前用户下的定时任务
crontab -e
#在该定时任务文件下,写入任务脚本,该任务表示每5分钟跑一次
5 * * * * sh/home/sh/helloworld.sh
  • 使用crontab -l来查看当前用户下的定时任务
1
2
3
4
[root@zyj sh]# crontab -l
*/3 * * * * sh /home/admin/edas-agent/bin/monitor.sh
5 * * * * sh/home/sh/helloworld.sh
[root@zyj sh]#

发现我们的定时任务,已经在当前用户下了

  • 具体各个用户的定时任务
1
2
3
4
5
6
7
[root@zyj sh]# cd /var/spool/cron/
[root@zyj cron]# ls
admin root
[root@zyj cron]# cat root
*/3 * * * * sh /home/admin/edas-agent/bin/monitor.sh
5 * * * * sh /home/sh/helloworld.sh
[root@zyj cron]#

可以看到当前root用户下的所有定时任务,同样道理也可以看到admin的

  • 通过定时任务日志来确定定时任务是否生效
1
2
3
4
#因为我们刚配置定时任务,需要重启服务生效
systemctl restart crond
#查看定时任务日志
tail -f /var/log/cron

定时任务日志

  • 删除定时任务
1
2
3
4
#删除当前用户下所有的定时任务,慎用
crontab -r
#删除指定定时任务,删除我们不需要的定时任务即可
crontab -e