定时任务相关命令

定时任务相关命令

Linux下的任务调度分为两类,系统任务调度和用户任务调度
系统任务调度就是系统周期性所要执行的工作,比如写缓存数据到硬盘、日志清理等,配置文件为/etc/crontab。
用户任务调度就是用户定期要执行的工作,即用户自己设定的定时计划任务,用户通过crontab命令设定的计划任务都被保存至/var/spool/cron/ 目录下,与当前用户同名的文件中。

1、日志目录:var/log/cron*

/var/log/cron只会记录是否执行了某些计划的脚本,具体执行是否正确以及脚本执行过程中的一些信息则linux会每次都发邮件到:/var/spool/mail/目录下的同用户名文件中。

[root@izwz91quxhnlkan8kjak5hz log]# ll cron*
-rw------- 1 root root 165895 8月  23 20:50 cron
-rw------- 1 root root 127713 7月  26 03:33 cron-20200726
-rw------- 1 root root 170330 8月   3 03:45 cron-20200803
-rw------- 1 root root 127744 8月   9 03:48 cron-20200809
-rw------- 1 root root 148410 8月  16 03:49 cron-20200816

2、定期执行程序的命令:crontab [ -u user ]

crond 命令每分锺会定期检查是否有要执行的工作,如果有要执行的工作便会自动执行该工作。
新创建的 cron 任务,不会马上执行,至少要过 2 分钟后才可以,当然你可以重启 cron 来马上执行

  • -u user 指定用户,如果不使用 -u user 的话,就是表示设定自己的时程表。
  • -e : 编辑定时任务时程表
  • -r : 删除定时任务时程表
  • -l : 列出定时任务时程表

3、 定时任务时间格式说明: f1 f2 f3 f4 f5 program

f1 是表示分钟,f2 表示小时,f3 表示一个月份中的第几日,f4 表示月份,f5 表示一个星期中的第几天。program 表示要执行的程序。

  • 当 f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程序,其馀类推
  • 当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,f2 为 a-b 时表示从第 a 到第 b 小时都要执行,其馀类推
  • 当 f1 为 */n 时表示每 n 分钟个时间间隔执行一次,f2 为 */n 表示每 n 小时个时间间隔执行一次,其馀类推
  • 当 f1 为 a, b, c,... 时表示第 a, b, c,... 分钟要执行,f2 为 a, b, c,... 时表示第 a, b, c...个小时要执行,其馀类推
[root@izwz91quxhnlkan8kjak5hz /]# cat /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
命令 注释
* * * * * echo ‘hello’ 每分钟执行一次,输出hello
0 6-12/3 * 12 * /usr/bin/backup 在 12 月内, 每天的早上 6 点到 12 点,每隔 3 个小时 0 分钟执行一次
0 17 * * 1-5 echo 'hello' 每星期一到星期五的下午5点执行一次,输出hello
cat /etc/passwd | cut -f 1 -d : |xargs -I {} crontab -l -u {} 查看所有用户的定时任务

4、crontab服务管理

命令 注释
systemctl status crond 查看crontab服务状态
systemctl start crond 开启crontab服务
systemctl stop crond 关闭crontab服务
systemctl restart crond 重启crontab服务
posted @ 2023-06-26 15:07  liuyang9643  阅读(52)  评论(0编辑  收藏  举报