一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

linux系统中Cron Job使用方法详解

时间:2016-06-22 编辑:简简单单 来源:一聚教程网

cron是linux的一个daemon,cron job就是被cron预定执行的任务。cron使用特殊的配置文件即crontab文件来设置命令或脚本的执行时间或频率。之前已经介绍crontab的基础使用,不再详述。
再次说明下crontab的命令格式

 # ┌───────────── min (0 - 59)
 # │ ┌────────────── hour (0 - 23)
 # │ │ ┌─────────────── day of month (1 - 31)
 # │ │ │ ┌──────────────── month (1 - 12)
 # │ │ │ │ ┌───────────────── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
 # │ │ │ │ │
 # │ │ │ │ │
 # * * * * *  command to execute

关于前五个参数日期和时间的表达:
表示任意:* 号表示 “任意”(first-last)。
指定数字,表示指定的时间。
指定段,表示“开始-结束”内包含的数:比如3-6,表示3,4,5,6
指定列表:比如 “1,2,3,4″,”0-4,8-12″
指定“步长”:8-14/2 表示8,10,12,14

然后看下面这条crontab表达式

0 0 5-20/5 2 2 /path/to/command

从2月5号到20号每5天执行一次外加2月的所有星期二,可见月和周参数都有指定值的时候(非*),它们是OR的关系。

另外crontab参数一些特殊预定义表达:

@yearly, @annually Run once a year at midnight of January 1 (0 0 1 1 *)
@monthly Run once a month, at midnight of the first day of the month (0 0 1 * *)
@weekly Run once a week at midnight of Sunday (0 0 * * 0)
@daily Run once a day at midnight (0 0 * * *)
@hourly Run at the beginning of every hour (0 * * * *)
@reboot Run once at startup

还可以执行多条命令,用;隔开

* * * * * /path/to/command-1; /path/to/command-2

如果命令间有依赖关系,可用逻辑运算符&&,如下如果第一条command失败,第二条command不会执行。

* * * * * /path/to/command-1 && /path/to/command-2

Contab可以设置重定向输出

* * * * * /path/to/php /path/to/the/command >> /var/log/cron.log

另外可以禁止cron发送邮件

* * * * * /path/to/php /path/to/the/command > /dev/null 2>&1

热门栏目