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 搜索之简单应用
Apr 27 PHP
PHP mb_convert_encoding 获取字符串编码类型实现代码
Apr 26 PHP
PHP正确配置mysql(apache环境)
Aug 28 PHP
将酷狗krc歌词解析并转换为lrc歌词php源码
Jun 20 PHP
php中通过DirectoryIterator删除整个目录的方法
Mar 13 PHP
PHP实现WebService的简单示例和实现步骤
Mar 27 PHP
PHP获得数组交集与差集的方法
Jun 10 PHP
关于php中的json_encode()和json_decode()函数的一些说明
Nov 20 PHP
php in_array() 检查数组中是否存在某个值详解
Nov 23 PHP
php微信公众号开发之答题连闯三关
Oct 20 PHP
laravel使用redis队列实例讲解
Mar 23 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
基于PHP导出Excel的小经验 完美解决乱码问题
2013/06/10 PHP
php+mysqli批量查询多张表数据的方法
2015/01/29 PHP
php cli模式下获取参数的方法
2017/05/05 PHP
PHP连接MySQL数据库三种实现方法
2020/12/10 PHP
php的单例模式及应用场景详解
2021/02/27 PHP
jquery $.getJSON()跨域请求
2011/12/21 Javascript
jquery 提交值不为空的元素示例代码
2013/05/10 Javascript
JS中三目运算符和if else的区别分析与示例
2014/11/21 Javascript
JS打字效果的动态菜单代码分享
2015/08/21 Javascript
JavaScript动态生成二维码图片
2016/04/20 Javascript
jQuery Validate插件实现表单验证
2016/08/19 Javascript
jQuery实现的导航下拉菜单效果示例
2016/09/05 Javascript
Angular实现表单验证功能
2017/11/13 Javascript
webpack中使用iconfont字体图标的方法
2018/02/22 Javascript
vue实现的上传图片到数据库并显示到页面功能示例
2018/03/17 Javascript
vue.js使用v-pre与v-html输出HTML操作示例
2018/07/07 Javascript
浅析Vue 和微信小程序的区别、比较
2018/08/03 Javascript
mpvue写一个CPASS小程序的示例
2018/09/04 Javascript
vue路由导航守卫和请求拦截以及基于node的token认证的方法
2019/04/07 Javascript
JavaScript实现图片伪异步上传过程解析
2020/04/10 Javascript
学习python处理python编码问题
2011/03/13 Python
利用QT写一个极简单的图形化Python闹钟程序
2015/04/07 Python
Flask框架的学习指南之开发环境搭建
2016/11/20 Python
使用python为mysql实现restful接口
2018/01/05 Python
使用python存储网页上的图片实例
2018/05/22 Python
Python Django 添加首页尾页上一页下一页代码实例
2019/08/21 Python
Django数据库操作之save与update的使用
2020/04/01 Python
Java ExcutorService优雅关闭方式解析
2020/05/30 Python
浅谈python处理json和redis hash的坑
2020/07/16 Python
详解Pytorch显存动态分配规律探索
2020/11/17 Python
幼师自荐信
2013/10/26 职场文书
关爱留守儿童倡议书
2014/04/15 职场文书
中职生求职信
2014/07/01 职场文书
党员对照检查材料整改措施思想汇报
2014/09/26 职场文书
住房公积金贷款工资证明
2015/06/12 职场文书
Vue操作Storage本地化存储
2022/04/29 Vue.js