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 相关文章推荐
图书管理程序(二)
Oct 09 PHP
基于MySQL体系结构的分析
May 02 PHP
PHP error_log()将错误信息写入一个文件(定义和用法)
Oct 25 PHP
php采集自中央气象台范围覆盖全国的天气预报代码实例
Jan 04 PHP
php中ob_flush函数和flush函数用法分析
Mar 18 PHP
php中preg_match的isU代表什么意思
Oct 01 PHP
PHP获取网站中各文章的第一张图片的代码示例
May 20 PHP
Ajax PHP JavaScript MySQL实现简易无刷新在线聊天室
Aug 17 PHP
PHP简单获取上月、本月、近15天、近30天的方法示例
Jul 03 PHP
php 读写json文件及修改json的方法
Mar 07 PHP
PHP函数积累总结
Mar 19 PHP
laravel通用化的CURD的实现
Dec 13 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
第十二节--类的自动加载
2006/11/16 PHP
PHP 判断常量,变量和函数是否存在
2009/04/26 PHP
php字符串分割函数用法实例
2015/03/17 PHP
php禁用函数设置及查看方法详解
2016/07/25 PHP
Symfony2获取web目录绝对路径、相对路径、网址的方法
2016/11/14 PHP
基于php编程规范(详解)
2017/08/17 PHP
laravel框架实现后台登录、退出功能示例
2019/10/31 PHP
PHP实现随机发放扑克牌
2020/04/21 PHP
自写的一个jQuery圆角插件
2010/10/26 Javascript
jQuery中 attr() 方法使用小结
2015/05/03 Javascript
JavaScript实现广告的关闭与显示效果实例
2015/07/02 Javascript
JS获取下拉框显示值和判断单选按钮的方法
2015/07/09 Javascript
Bootstrap 附加导航(Affix)插件实例详解
2016/06/01 Javascript
利用jquery获取select下拉框的值
2016/11/23 Javascript
原生js开发的日历插件
2017/02/04 Javascript
vue数据传递--我有特殊的实现技巧
2018/03/20 Javascript
js实现数字从零慢慢增加到指定数字示例
2019/11/07 Javascript
何时/使用 Vue3 render 函数的教程详解
2020/07/25 Javascript
详解Vue.js 可拖放文本框组件的使用
2021/03/03 Vue.js
在Python中封装GObject模块进行图形化程序编程的教程
2015/04/14 Python
举例讲解Python中的Null模式与桥接模式编程
2016/02/02 Python
Python实现基本数据结构中队列的操作方法示例
2017/12/04 Python
python机器学习之KNN分类算法
2018/08/29 Python
Python语言异常处理测试过程解析
2020/01/08 Python
Keras官方中文文档:性能评估Metrices详解
2020/06/15 Python
pytorch VGG11识别cifar10数据集(训练+预测单张输入图片操作)
2020/06/24 Python
python cv2.resize函数high和width注意事项说明
2020/07/05 Python
adidas澳大利亚官方网站:adidas Australia
2018/04/15 全球购物
英国信箱在线鲜花速递公司:Bloom & Wild
2019/03/10 全球购物
《千年梦圆在今朝》教学反思
2014/02/24 职场文书
幼儿园大班毕业教师寄语
2014/04/03 职场文书
幼儿园中班下学期评语
2014/04/18 职场文书
村党支部书记四风问题个人对照检查材料思想汇报
2014/10/06 职场文书
承诺书模板大全
2015/05/04 职场文书
创业计划书之家政服务
2019/09/18 职场文书
一篇文章弄清楚Ajax请求的五个步骤
2022/03/17 Javascript