linux crontab 定时计划

在linux里允许自动在后台运行一些定时的计划任务。我们可以用它来自动备份,同步文件,计划定时更新等。实现计划任务,让我们来定制自己的crontab。

常用的crontab命令有

1、查看所用的计划任务 crontab -l  

打开终端运行如下命令

可以看到

* 13  * * * php /var/www/log.php

可以看到该计划任务为运行一个php脚本,定时是怎么实现呢?是通过前面的五个参数来实现的,分别对应上面的 m  h dom mon dow command

minute(from 0 to 59)

hour(from 0 to 23)

day of month(from 1 to 31)

month(from 1 to 12)

day of week(from 0 to 6)(0=Sunday)

command 用定时执行的命令

上面的命令为每天中午一点每分钟执行log.php脚本

我们来看一下,log.php脚本。这是一个log日志操作类

View Code
 1 <?php
 2 
 3 class lufLog {
 4 
 5     private $name;
 6     //路径
 7     private $path = "/var/www/mylog.txt";
 8     //级别
 9     private $leve = array('DEBUG' => 'DEBUG',
10         'INFO' => 'INFO',
11         'WARNING' => 'WARNING',
12         'ERROR' => 'ERROR');
13 
14     public function __construct($name) {
15         $this->name = $name;
16     }
17 
18     public function Log($leve, $content) {
19         $Leve = $this->leve[$leve];
20         $this->WriteLog($this->name . "[$Leve]:" . $content . "\n");
21     }
22 
23     private function WriteLog($content) {
24         if (!file_exists($this->path)) {
25             echo $this->path;
26             fopen($this->path, 'w');
27         }
28         file_put_contents($this->path, $content, FILE_APPEND);
29     }
30 
31 }
32 
33 $log = new lufLog('mylog');
34 $log->Log('INFO', print_r(date('Y-m-d H:i:s', time()), true));
35 ?>

2.打开mylog.txt可以看到

3.编写定时任务命令为 crontab -e

4.一些参考

0    1   *  *   5     每周5早上一点运行

0    1   *  *   1-5  每周1到周5早上一点运行

10  *    1  *  *      每个月的第一天的每个小时的第十分钟运行

*/10  *  *  *  *     每十分钟运行

5.一些特殊的时间

6.使用字符设置时间

其他详细使用可以参考:http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/

posted on 2013-04-27 11:57  d&lufd  阅读(813)  评论(0编辑  收藏  举报

导航