linux定时任务之cron

cron定时任务

简介

cron是linux系统提供的一种执行定时任务的服务,在后台运行,通过配置文件“crontab”来根据时间调度指定的任务执行。这些定时任务可以分为两种,一种是系统任务,一种是用户任务。

定时执行原理

cron启动时会加载/var/spool/cron/crontabs目录下的配置文件以及/etc/crontab配置文件到内存。然后,cron服务进程每分钟检测一下这些crontab,看看有那些命令需要在这分钟执行。如果有需要执行的,就执行相关命令。另外,cron还会检测配置文件的修改时间,如果发生变化,则重新加载所有crontabs,因此,我们不必在修改crontab后重启服务来激活这些定时任务。

cron配置文件

  • /var/spool/cron/ 目录下存放的是每个用户包括root的crontab任务,每个任务以创建者的名字命名
  • /etc/crontab 这个文件负责调度各种系统管理和维护任务。
  • /etc/cron.d/ 这个目录用来存放任何要执行的crontab文件或脚本。
  • 我们还可以把配置文件放在
    /etc/cron.hourly、/etc/cron.daily、/etc/cron.weekly、/etc/cron.monthly目录中,让它每小时/天/星期/月执行一次。

cron语法

* * * * * command to be executed
- - - - - -
| | | | | |
| | | | | --- 预执行的命令
| | | | ----- 表示星期0~7(其中星期天可以用0或7表示)
| | | ------- 表示月份1~12
| | --------- 表示日期1~31
| ----------- 表示小时1~23(0表示0点)
------------- 表示分钟1~59 每分钟用*或者 */1表示

系统任务

这些cron任务被系统服务和关键任务所使用,且需要root级的权限才能执行。可以在/etc/crontab文件中查看系统级的cron作业

[root@localhost etc]# 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

* * * * * root /root/test.sh

用户任务

用户级的cron任务是针对每个用户单独分开的。因此每个用户都可以使用crontab命令创建自己的cron作业,还可以使用以下命令编辑或查看自己的cron作业。

使用crontab -e命令编辑用户定义的cron任务。

# use /bin/bash to run commands, instead of the default /bin/sh
SHELL=/bin/bash
# mail any output to `paul', no matter whose crontab this is
MAILTO=paul
#
# run five minutes after midnight, every day
5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
# run at 2:15pm on the first of every month — output mailed to paul
15 14 1 * *     $HOME/bin/monthly
# run at 10 pm on weekdays, annoy Joe
0 22 * * 1–5    mail -s "It's 10pm" joe%Joe,%%Where are your kids?%
23 0–23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"
5 4 * * sun     echo "run at 5 after 4 every Sunday"
0 */4 1 * mon   echo "run every 4th hour on the 1st and on every Monday"
0 0 */2 * sun   echo "run at midn on every Sunday that's an uneven date"
# Run on every second Saturday of the month
0 4 8–14 * *    test $(date +\%u) -eq 6 && echo "2nd Saturday"

All the above examples run non-interactive programs.  If you wish to run a pro‐
gram that interacts with the user's desktop you have to make  sure  the  proper
environment variable DISPLAY is set.

# Execute a program and run a notification every day at 10:00 am
0 10 * * *  $HOME/bin/program | DISPLAY=:0 notify-send "Program run" "$(cat)"

posted @ 2020-09-10 16:14  ZhaoKevin  阅读(693)  评论(0编辑  收藏  举报