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 相关文章推荐
php图片加水印原理(超简单的实例代码)
Jan 18 PHP
PHP中对于浮点型的数据需要用不同的方法解决
Mar 11 PHP
ThinkPHP中U方法的使用浅析
Jun 13 PHP
php查询mysql数据库并将结果保存到数组的方法
Mar 18 PHP
php session 写入数据库
Feb 13 PHP
Yii2创建控制器(createController)方法详解
Jul 23 PHP
PHP入门教程之使用Mysqli操作数据库的方法(连接,查询,事务回滚等)
Sep 11 PHP
PHP 接入微信扫码支付总结(总结篇)
Nov 03 PHP
注释PHP和html混合代码的小技巧(分享)
Nov 03 PHP
PHP使用两个栈实现队列功能的方法
Jan 15 PHP
laravel框架中路由设置,路由参数和路由命名实例分析
Nov 23 PHP
PHP超级全局变量【$GLOBALS,$_SERVER,$_REQUEST等】用法实例分析
Dec 11 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
WordPress中查询文章的循环Loop结构及用法分析
2015/12/17 PHP
PHP实现的oracle分页函数实例
2016/01/25 PHP
PHP中危险的file_put_contents函数详解
2017/11/04 PHP
文字幻灯片
2006/06/26 Javascript
javascript js cookie的存储,获取和删除
2007/12/29 Javascript
JQuery 常用方法和事件详细介绍
2013/04/18 Javascript
jquery结合CSS使用validate实现漂亮的验证
2015/01/29 Javascript
jQuery验证元素是否为空的两种常用方法
2015/03/17 Javascript
原生Js实现简易烟花爆炸效果的方法
2015/03/20 Javascript
jQuery实现仿新浪微博浮动的消息提示框(可智能定位)
2015/10/10 Javascript
jQuery表单验证简单示例
2016/10/17 Javascript
Vue + Vue-router 同名路由切换数据不更新的方法
2017/11/20 Javascript
Vuejs在v-for中,利用index来对第一项添加class的方法
2018/03/03 Javascript
Vue多系统切换实现方案
2018/06/05 Javascript
swiper在vue项目中loop循环轮播失效的解决方法
2018/09/15 Javascript
ztree加载完成后显示勾选节点的实现代码
2018/10/22 Javascript
node.js +mongdb实现登录功能
2020/06/18 Javascript
[55:02]2014 DOTA2国际邀请赛中国区预选赛 HGT VS Orenda
2014/05/21 DOTA
[01:13:17]Secret vs NB 2018国际邀请赛小组赛BO2 第二场 8.19
2018/08/21 DOTA
十条建议帮你提高Python编程效率
2016/02/16 Python
浅析python3字符串格式化format()函数的简单用法
2018/12/07 Python
Django 日志配置按日期滚动的方法
2019/01/31 Python
pytorch:torch.mm()和torch.matmul()的使用
2019/12/27 Python
python else语句在循环中的运用详解
2020/07/06 Python
python 简单的调用有道翻译
2020/11/25 Python
Radley英国官网:英国莱德利小狗包
2019/03/21 全球购物
2013年学期结束动员演讲稿
2014/01/07 职场文书
社区端午节活动方案
2014/01/28 职场文书
《小白兔和小灰兔》教学反思
2014/02/18 职场文书
应届毕业生自荐信例文
2014/02/26 职场文书
小班开学寄语
2014/04/04 职场文书
家长会欢迎词
2015/01/23 职场文书
员工自我工作评价
2015/03/06 职场文书
几款流行的HTML5 UI框架比较(小结)
2021/04/08 HTML / CSS
36个正则表达式(开发效率提高80%)
2021/11/17 Javascript
JPA 通过Specification如何实现复杂查询
2021/11/23 Java/Android