PHP中实现crontab代码分享


Posted in PHP onMarch 26, 2015

1. 准备一个标准crontab文件 ./crontab

# m h dom mon dow command

* * * * * date > /tmp/cron.date.run

2. crontab -e 将此cron.php脚本加入系统cron

* * * * * /usr/bin/php cron.php

3. cron.php 源码

// 从./crontab读取cron项,也可以从其他持久存储(mysql、redis)读取

$crontab = file('./crontab');

$now = $_SERVER['REQUEST_TIME'];
foreach ( $crontab as $cron ) {

 $slices = preg_split("/[\s]+/", $cron, 6);

 if( count($slices) !== 6 ) continue;
 $cmd       = array_pop($slices);

 $cron_time = implode(' ', $slices);

 $next_time = Crontab::parse($cron_time, $now);

 if ( $next_time !== $now ) continue; 
 $pid = pcntl_fork();

 if ($pid == -1) {

  die('could not fork');

 } else if ($pid) {

  // we are the parent

  pcntl_wait($status, WNOHANG); //Protect against Zombie children

 } else {

      // we are the child

  `$cmd`;

  exit;

 }

}
/* https://github.com/jkonieczny/PHP-Crontab */

class Crontab {

   /**

 * Finds next execution time(stamp) parsin crontab syntax,

 * after given starting timestamp (or current time if ommited)

 *

 * @param string $_cron_string:

 *

 * 0 1 2 3 4

 * * * * * *

 * - - - - -

 * | | | | |

 * | | | | +----- day of week (0 - 6) (Sunday=0)

 * | | | +------- month (1 - 12)

 * | | +--------- day of month (1 - 31)

 * | +----------- hour (0 - 23)

 * +------------- min (0 - 59)

 * @param int $_after_timestamp timestamp [default=current timestamp]

 * @return int unix timestamp - next execution time will be greater

 * than given timestamp (defaults to the current timestamp)

 * @throws InvalidArgumentException

 */

    public static function parse($_cron_string,$_after_timestamp=null)

    {

        if(!preg_match('/^((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)$/i',trim($_cron_string))){

            throw new InvalidArgumentException("Invalid cron string: ".$_cron_string);

        }

        if($_after_timestamp && !is_numeric($_after_timestamp)){

            throw new InvalidArgumentException("\$_after_timestamp must be a valid unix timestamp ($_after_timestamp given)");

        }

        $cron = preg_split("/[\s]+/i",trim($_cron_string));

        $start = empty($_after_timestamp)?time():$_after_timestamp;
        $date = array( 'minutes' =>self::_parseCronNumbers($cron[0],0,59),

                            'hours' =>self::_parseCronNumbers($cron[1],0,23),

                            'dom' =>self::_parseCronNumbers($cron[2],1,31),

                            'month' =>self::_parseCronNumbers($cron[3],1,12),

                            'dow' =>self::_parseCronNumbers($cron[4],0,6),

                        );

        // limited to time()+366 - no need to check more than 1year ahead

        for($i=0;$i<=60*60*24*366;$i+=60){

            if( in_array(intval(date('j',$start+$i)),$date['dom']) &&

                in_array(intval(date('n',$start+$i)),$date['month']) &&

                in_array(intval(date('w',$start+$i)),$date['dow']) &&

                in_array(intval(date('G',$start+$i)),$date['hours']) &&

                in_array(intval(date('i',$start+$i)),$date['minutes'])
                ){

                    return $start+$i;

            }

        }

        return null;

    }
    /**

 * get a single cron style notation and parse it into numeric value

 *

 * @param string $s cron string element

 * @param int $min minimum possible value

 * @param int $max maximum possible value

 * @return int parsed number

 */

    protected static function _parseCronNumbers($s,$min,$max)

    {

        $result = array();
        $v = explode(',',$s);

        foreach($v as $vv){

            $vvv = explode('/',$vv);

            $step = empty($vvv[1])?1:$vvv[1];

            $vvvv = explode('-',$vvv[0]);

            $_min = count($vvvv)==2?$vvvv[0]:($vvv[0]=='*'?$min:$vvv[0]);

            $_max = count($vvvv)==2?$vvvv[1]:($vvv[0]=='*'?$max:$vvv[0]);
            for($i=$_min;$i<=$_max;$i+=$step){

                $result[$i]=intval($i);

            }

        }

        ksort($result);

        return $result;

    }

}
PHP 相关文章推荐
基于mysql的bbs设计(一)
Oct 09 PHP
php在页面中调用fckeditor编辑器的方法
Jun 10 PHP
PHP array操作10个小技巧分享
Jun 23 PHP
PHP处理excel cvs表格的方法实例介绍
May 13 PHP
如何在php中正确的使用json
Aug 06 PHP
浅析ThinkPHP中的pathinfo模式和URL重写
Jan 06 PHP
php cli换行示例
Apr 22 PHP
php随机取mysql记录方法小结
Dec 27 PHP
WordPress自定义时间显示格式
Mar 27 PHP
PHP实现简单实用的验证码类
Jul 29 PHP
PHP实现的函数重载功能示例
Aug 03 PHP
PHP 实现缩略图
Mar 09 PHP
PHP利用hash冲突漏洞进行DDoS攻击的方法分析
Mar 26 #PHP
ThinkPHP、ZF2、Yaf、Laravel框架路由大比拼
Mar 25 #PHP
CentOS 安装 PHP5.5+Redis+XDebug+Nginx+MySQL全纪录
Mar 25 #PHP
MacOS 安装 PHP的图片裁剪扩展Tclip
Mar 25 #PHP
php编写的一个E-mail验证类
Mar 25 #PHP
php取得字符串首字母的方法
Mar 25 #PHP
PHP判断IP并转跳到相应城市分站的方法
Mar 25 #PHP
You might like
PHP5.3.1 不再支持ISAPI
2010/01/08 PHP
PHP中使用foreach和引用导致程序BUG的问题介绍
2012/09/05 PHP
PHP中使用break跳出多重循环代码实例
2015/01/21 PHP
ThinkPHP3.2.2实现持久登录(记住我)功能的方法
2016/05/16 PHP
js 遍历对象的属性的代码
2011/12/29 Javascript
JS文本框默认值处理详解
2013/07/10 Javascript
js兼容的placeholder属性详解
2013/08/18 Javascript
jQuery操作CheckBox的方法介绍(选中,取消,取值)
2014/02/04 Javascript
jquery动态加载js/css文件方法(自写小函数)
2014/10/11 Javascript
js中hash和ico的关联分析
2015/02/05 Javascript
JavaScript中eval函数的问题
2016/01/31 Javascript
jQuery操作json常用方法示例
2017/01/04 Javascript
jstree单选功能的实现方法
2017/06/07 Javascript
JS实现深度优先搜索求解两点间最短路径
2019/01/17 Javascript
浅谈Javascript中的对象和继承
2019/04/19 Javascript
微信小程序搭建自己的Https服务器
2019/05/02 Javascript
使用Python获取CPU、内存和硬盘等windowns系统信息的2个例子
2014/04/15 Python
Python lambda函数基本用法实例分析
2018/03/16 Python
关于Python正则表达式 findall函数问题详解
2018/03/22 Python
Python批量合并有合并单元格的Excel文件详解
2018/04/05 Python
Python解压 rar、zip、tar文件的方法
2019/11/19 Python
matplotlib quiver箭图绘制案例
2020/04/17 Python
一文轻松掌握python语言命名规范规则
2020/06/18 Python
Python实现弹球小游戏
2020/08/01 Python
CSS3中的注音对齐属性ruby-align用法指南
2016/07/01 HTML / CSS
StubHub新西兰:购买和出售你的门票
2019/04/22 全球购物
Servlet都有哪些方法?主要作用是什么?
2014/03/04 面试题
医学院学生的自我评价分享
2013/11/19 职场文书
餐饮主管岗位职责
2013/12/10 职场文书
安全承诺书格式
2014/05/21 职场文书
保护水资源的标语
2014/06/17 职场文书
党员四风问题个人对照检查材料
2014/10/26 职场文书
2014年新教师工作总结
2014/11/08 职场文书
离婚协议书样本
2015/01/26 职场文书
入党转正申请报告
2015/05/15 职场文书
心术观后感
2015/06/11 职场文书