PHP中实现crontab代码分享_php实例

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;
    }
}

时间: 2024-09-08 05:02:46

PHP中实现crontab代码分享_php实例的相关文章

PHP中实现crontab代码分享

 这篇文章主要介绍了PHP中实现crontab代码分享,本文给出了实现代码和使用方法,需要的朋友可以参考下     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 源码

使用PHPMailer实现邮件发送代码分享_php实例

发送邮件是常用的功能,LZ今天在项目中也碰到了,特此分享一下. 首先,去下载PHPMailer 1.https://github.com/dwqs/PHPMailer 2.http://download.csdn.net/detail/u011043843/8063583 下载之后,将文件解压到项目目录的对应位置,将class.phpmailer.php和class.smtp.php引入项目中,看代码:(解压的文件不要删除,否则不行) <?php // 必要导入 require("clas

php等比例缩放图片及剪切图片代码分享_php实例

php等比例缩放图片及剪切图片代码分享 /** * 图片缩放函数(可设置高度固定,宽度固定或者最大宽高,支持gif/jpg/png三种类型) * Author : Specs * * @param string $source_path 源图片 * @param int $target_width 目标宽度 * @param int $target_height 目标高度 * @param string $fixed_orig 锁定宽高(可选参数 width.height或者空值) * @ret

PHP Web木马扫描器代码分享_php实例

不废话了,直接贴代码了. 代码如下: <?php header('content-type:text/html;charset=gbk'); set_time_limit(0);//防止超时 /** * * php目录扫描监控增强版 * * @version 1.0 * 下面几个变量使用前需要手动设置 * **/ /*===================== 程序配置 =====================*/ $pass="test";//设置密码 $jkdir=&quo

php调用dll的实例操作动画与代码分享_php实例

动画中的原代码如下: 复制代码 代码如下: VERSION 1.0 CLASS BEGIN MultiUse = -1 'True Persistable = 0 'NotPersistable DataBindingBehavior = 0 'vbNone DataSourceBehavior = 0 'vbNone MTSTransactionMode = 0 'NotAnMTSObject END Attribute VB_Name = "tw" Attribute VB_Glo

PHP开发微信支付的代码分享_php实例

微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布.必须到你通过程序测试提交订单.发货通知等数据到微信的系统中,才能申请发布. 然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到二级三级目录下去,这对于使用MVC框架来说,是个小问题. 使用MVC,在开发环境,url往往是native url格式,不能保证一定是带有路径/的形式 所以,比较可靠的方式,是创建实体的子文件夹,这样的化,在系统整体url方面,需要进行一些改造. 另外,最后一步,js调用时,对于

PHP中数据库单例模式的实现代码分享_php实例

首先我们要知道明确单例模式这个概念,那么什么是单例模式呢? 单例模式顾名思义,就是只有一个实例. 作为对象的创建模式, 单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类我们称之为单例类. 单例模式的要点有三个: 一是某个类只能有一个实例: 二是它必须自行创建这个实例: 三是它必须自行向整个系统提供这个实例. 下面我们讨论下为什么要使用PHP单例模式? 多数人都是从单例模式的字面上的意思来理解它的用途, 认为这是对系统资源的节省, 可以避免重复实例化, 是一种"计划

PHP实现Javascript中的escape及unescape函数代码分享_php实例

这个类相当好用.作用么,PHP做JSON传递GBK字符,比如中文,日文,韩文神马的Unicode最合适不过了.. <?php classcoding { //模仿JAVASCRIPT的ESCAPE和UNESCAPE函数的功能 functionunescape($str) { $text=preg_replace_callback("/%u[0-9A-Za-z]{4}/",array( &$this, 'toUtf8' ),$str); returnmb_convert_e

PHP微信红包生成代码分享_php实例

本文实例为大家分享了PHP微信公众号自动发送红包API代码,分享给大家供大家参考.具体如下: 贴出核心接口代码至于数据自己填写,接口测试OKwechat_packet.php <!--?php /** * 发送红包接口 * Created by PhpStorm. * User: ADKi * Date: 2016/4/25 0025 * Time: 15:25 */ class wechat_packet{ private $url = 'https://api.mch.weixin.qq.c