THINKPHP的cron任务实现

THINKPHP的cron任务实现

THINKPHP的cron计划任务的实现,利用THINKPHP自带的cli,加上数据库执行记录(记录任务的报错,成功)。

在服务器cron定时任务在网站目录(不是网站根目录)执行php cron.php,网站根目录为Public。

1.jpg

写一个cli的入口文件

立即学习“PHP免费学习笔记(深入)”;

cli.php

<?phpdefine('MODE_NAME', 'cli');// 检测PHP环境if(version_compare(PHP_VERSION,'5.3.0',' 5.3.0 !');define('APP_DEBUG', true);// 定义应用目录define('APP_PATH', __DIR__ . '/Application/');// 引入ThinkPHP入口文件require __DIR__ . '/ThinkPHP/ThinkPHP.php';

写一个执行文件

cron.php

define('AUTO_CRON', true);include __DIR__ . '/cli.php';

数据库设计

DROP TABLE IF EXISTS `cron`;CREATE TABLE IF NOT EXISTS `cron` (  `cron_id` int(10) unsigned NOT NULL AUTO_INCREMENT,  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',  `expression` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',  `class` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',  `method` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',  `type` varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',  `status` varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',  `run_at` timestamp NULL DEFAULT NULL,  `ms` int(10) unsigned NOT NULL DEFAULT '0',  `error` text COLLATE utf8_unicode_ci NOT NULL,  PRIMARY KEY (`cron_id`),  KEY `name` (`name`,`created_at`),  KEY `cron_status_index` (`status`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

配置文件

 '1.0.0',    'beastalkd' => array(        'process_untreated_queue' => array(            'expression' => '* * * * *',            'class' => 'StatisticsModelPheanstalkModel',            'method' => 'processUntreatedQueue'        )    ));

执行文件 init.php  

/写个hook程序执行init.php

query("SHOW TABLES LIKE 'cron'")?false:true;if(defined("AUTO_CRON") && $Has){    class CronCommand    {        protected $_initializedJobs;        protected $_jobs;        protected $_now;        public function __construct()        {            $this->_now = strtotime(date('Y-n-j H:i'));            import("Cron.Common.Cron.tdcron_entry",'','.php');            import("Cron.Common.Cron.tdcron",'','.php');        }        /**         * 这里是放要执行的代码         */        public function fire()        {            restore_error_handler();            restore_exception_handler();            $this->_initializedJobs = array();            $jobs = M('cron')->where("status = 'initialized'")->select();            /**             * @var $cron Cron             * 已存在 cron             */            if($jobs) {                $cron = new Cron();                foreach ($jobs as $data) {                    $cron->setData($data)->isNew(false);                    $this->_initializedJobs[$data['name']] = $cron;                }            }            /**             * 新 cron             */            foreach ($this->getCronJobs() as $name => $cronJob) {                if (isset($cronJob['expression'])) {                    $expression = $cronJob['expression'];                } else {                    Log::write('Cron expression is required for cron job "' . $name . '"',Log::WARN);                    continue;                }                if ($this->_now != tdCron::getNextOccurrence($expression, $this->_now)) continue;                $cronJob['name'] = $name;                $cron = isset($this->_initializedJobs[$name]) ? $this->_initializedJobs[$name] : $this->_initializedJobs[$name] = new Cron();                $cron->initialize($cronJob);            }            /* @var $cron Cron 处理*/            foreach ($this->_initializedJobs as $cron) {                $cron->run();            }        }        /**         * Get All Defined Cron Jobs         * 获取配置         * @return array         */        public function getCronJobs()        {            if ($this->_jobs === null) {                $this->_jobs = C('beastalkd');            }            return $this->_jobs;        }    }    $command = new CronCommand();    $command->fire();}

cron 模型

 $v) {            $this->setData($k, $v);        }        $now = date('Y-m-d H:i:s');        $this->setData('status',self::STATUS_INITIALIZED)->setData('created_at',$now)->setData('updated_at',$now)->save();        return $this;    }    /**     * @return $this  run 命令     */    public function run()    {        $this->setData('run_at',date('Y-m-d H:i:s'))->setData('status',self::STATUS_RUNNING)->save();        Timer::start();        try {            $class = $this->getData('class');            $method = $this->getData('method');            if (!class_exists($class)) throw new Exception(sprintf('Class "%s" not found!', $class));            if (!method_exists($class, $method)) throw new Exception(sprintf('Method "%s::%s()" not found!', $class, $method));            $callback = array($this->getSingleton($class), $method);            //new CLASS 使用操作方法            // 执行配置里的 StatisticsModelPheanstalkModel类 的 processUntreatedQueue 操作             call_user_func($callback);            Timer::stop();            $this->setData('ms',round(Timer::diff() * 1000))->setData('status',self::STATUS_COMPLETED)->save();        } catch (Exception $e) {            Timer::stop();            $this->setData('ms',round(Timer::diff() * 1000))                ->setData('status',self::STATUS_FAILED)                ->setData('error',$e->getMessage() . "nParams:n" . var_export($this->getDbFields(), true))->save();            Log::write($e->getMessage() . "n" . $e->getTraceAsString(),Log::ERR);        }        return $this;    }}

CommonModel 模型

_jsonFields as $field) {         is_string($_data = fnGet($result, $field)) and $result[$field] = json_decode($_data, true);      }      $this->_originalData = $result;      $this->_isNew = !$result;      parent::_after_find($result, $options);   }   protected function _after_save($result) {   }   protected function _before_find() {      $this->_originalData = array();   }   protected function _facade($data) {      foreach ($this->_jsonFields as $field) {         is_array($_data = fnGet($data, $field)) and $data[$field] = json_encode($_data);      }      return parent::_facade($data);   }   public function find($options = array()) {      $this->_before_find();      return parent::find($options);   }   public function getData($key = null) {      return $key === null ? $this->data : $this->__get($key);   }   public function getOptions() {      return $this->options;   }   public function getOriginalData($key = null) {      return $key === null ? $this->_originalData : fnGet($this->_originalData, $key);   }   /**    * Get or set isNew flag    *    * @param bool $flag    *    * @return bool    */   public function isNew($flag = null) {      if ($flag !== null) $this->_isNew = (bool)$flag;      return $this->_isNew;   }   public function save($data = '', $options = array()) {      if ($this->_isNew) {         $oldData = $this->data;         $result = $this->add($data, $options);         $this->data = $oldData;         if ($result && $this->pk && is_string($this->pk)) {            $this->setData($this->pk, $result);         }         $this->_isNew = false;      } else {         $oldData = $this->data;         $result = parent::save($data, $options);         $this->data = $oldData;      }      $this->_after_save($result);      return $result;   }   public function setData($key, $value = null) {      is_array($key) ?         $this->data = $key :         $this->data[$key] = $value;      return $this;   }}

Timer.class.php

<?phpnamespace CronModel;class Timer{    protected static $_start = array(0, 0);    protected static $_stop = array(0, 0);    public static function diff($start = null, $stop = null)    {        $start and self::start($start);        $stop and self::stop($stop);        return (self::$_stop[0] - self::$_start[0]) + (self::$_stop[1] - self::$_start[1]);    }    public static function start($microtime = null)    {        $microtime or $microtime = microtime();        self::$_start = explode(' ', $microtime);    }    public static function stop($microtime = null)    {        $microtime or $microtime = microtime();        self::$_stop = explode(' ', $microtime);    }}

tdcron.php

<?phpdefine('IDX_MINUTE', 0);define('IDX_HOUR', 1);define('IDX_DAY', 2);define('IDX_MONTH', 3);define('IDX_WEEKDAY', 4);define('IDX_YEAR', 5);/* * tdCron v0.0.1 beta - CRON-Parser for PHP * * Copyright (c) 2010 Christian Land / tagdocs.de * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Christian Land  * @package    tdCron * @copyright  Copyright (c) 2010, Christian Land / tagdocs.de * @version    v0.0.1 beta */class tdCron{   /**    * Parsed cron-expressions cache.    * @var mixed    */   static private $pcron = array();   /**    * getNextOccurrence() uses a cron-expression to calculate the time and date at which a cronjob    * should be executed the next time. If a reference-time is passed, the next time and date    * after that time is calculated.    *    * @access    public    * @param     string $expression cron-expression to use    * @param     int $timestamp optional reference-time    * @return    int    * @throws    Exception    */   static public function getNextOccurrence($expression, $timestamp = null)   {      try {         // Convert timestamp to array         $next = self::getTimestamp($timestamp);         // Calculate date/time         $next_time = self::calculateDateTime($expression, $next);      } catch (Exception $e) {         throw $e;      }      // return calculated time      return $next_time;   }   /**    * getLastOccurrence() does pretty much the same as getNextOccurrence(). The only difference    * is, that it doesn't calculate the next but the last time a cronjob should have been executed.    *    * @access    public    * @param     string $expression cron-expression to use    * @param     int $timestamp optional reference-time    * @return    int    * @throws    Exception    */   static public function getLastOccurrence($expression, $timestamp = null)   {      try {         // Convert timestamp to array         $last = self::getTimestamp($timestamp);         // Calculate date/time         $last_time = self::calculateDateTime($expression, $last, false);      } catch (Exception $e) {         throw $e;      }      // return calculated time      return $last_time;   }   /**    * calculateDateTime() is the function where all the magic happens :-)    *    * It calculates the time and date at which the next/last call of a cronjob is/was due.    *    * @access    private    * @param     mixed $expression cron-expression    * @param     mixed $rtime reference-time    * @param     bool $next true = nextOccurence, false = lastOccurence    * @return    int    * @throws    Exception    */   static private function calculateDateTime($expression, $rtime, $next = true)   {      // Initialize vars      $calc_date = true;      // Parse cron-expression (if neccessary)      $cron = self::getExpression($expression, !$next);      // OK, lets see if the day/month/weekday of the reference-date exist in our      // $cron-array.      if (!in_array($rtime[IDX_DAY], $cron[IDX_DAY]) || !in_array($rtime[IDX_MONTH], $cron[IDX_MONTH]) || !in_array($rtime[IDX_WEEKDAY], $cron[IDX_WEEKDAY])) {         // OK, things are easy. The day/month/weekday of the reference time         // can't be found in the $cron-array. This means that no matter what         // happens, we WILL end up at at a different date than that of our         // reference-time. And in this case, the lastOccurrence will ALWAYS         // happen at the latest possible time of the day and the nextOccurrence         // at the earliest possible time.         //         // In both cases, the time can be found in the first elements of the         // hour/minute cron-arrays.         $rtime[IDX_HOUR] = reset($cron[IDX_HOUR]);         $rtime[IDX_MINUTE] = reset($cron[IDX_MINUTE]);      } else {         // OK, things are getting a little bit more complicated...         $nhour = self::findValue($rtime[IDX_HOUR], $cron[IDX_HOUR], $next);         // Meh. Such a cruel world. Something has gone awry. Lets see HOW awry it went.         if ($nhour === false) {            // Ah, the hour-part went wrong. Thats easy. Wrong hour means that no            // matter what we do we'll end up at a different date. Thus we can use            // some simple operations to make things look pretty ;-)            //            // As alreasy mentioned before -> different date means earliest/latest            // time:            $rtime[IDX_HOUR] = reset($cron[IDX_HOUR]);            $rtime[IDX_MINUTE] = reset($cron[IDX_MINUTE]);            // Now all we have to do is add/subtract a day to get a new reference time            // to use later to find the right date. The following line probably looks            // a little odd but thats the easiest way of adding/substracting a day without            // screwing up the date. Just trust me on that one ;-)            $rtime = explode(',', strftime('%M,%H,%d,%m,%w,%Y', mktime($rtime[IDX_HOUR], $rtime[IDX_MINUTE], 0, $rtime[IDX_MONTH], $rtime[IDX_DAY], $rtime[IDX_YEAR]) + ((($next) ? 1 : -1) * 86400)));         } else {            // OK, there is a higher/lower hour available. Check the minutes-part.            $nminute = self::findValue($rtime[IDX_MINUTE], $cron[IDX_MINUTE], $next);            if ($nminute === false) {               // No matching minute-value found... lets see what happens if we substract/add an hour               $nhour = self::findValue($rtime[IDX_HOUR] + (($next) ? 1 : -1), $cron[IDX_HOUR], $next);               if ($nhour === false) {                  // No more hours available... add/substract a day... you know what happens ;-)                  $nminute = reset($cron[IDX_MINUTE]);                  $nhour = reset($cron[IDX_HOUR]);                  $rtime = explode(',', strftime('%M,%H,%d,%m,%w,%Y', mktime($nhour, $nminute, 0, $rtime[IDX_MONTH], $rtime[IDX_DAY], $rtime[IDX_YEAR]) + ((($next) ? 1 : -1) * 86400)));               } else {                  // OK, there was another hour. Set the right minutes-value                  $rtime[IDX_HOUR] = $nhour;                  $rtime[IDX_MINUTE] = (($next) ? reset($cron[IDX_MINUTE]) : end($cron[IDX_MINUTE]));                  $calc_date = false;               }            } else {               // OK, there is a matching minute... reset minutes if hour has changed               if ($nhour  $rtime[IDX_HOUR]) {                  $nminute = reset($cron[IDX_MINUTE]);               }               // Set time               $rtime[IDX_HOUR] = $nhour;               $rtime[IDX_MINUTE] = $nminute;               $calc_date = false;            }         }      }      // If we have to calculate the date... we'll do so      if ($calc_date) {         if (in_array($rtime[IDX_DAY], $cron[IDX_DAY]) && in_array($rtime[IDX_MONTH], $cron[IDX_MONTH]) && in_array($rtime[IDX_WEEKDAY], $cron[IDX_WEEKDAY])) {            return mktime($rtime[1], $rtime[0], 0, $rtime[3], $rtime[2], $rtime[5]);         } else {            // OK, some searching necessary...            $cdate = mktime(0, 0, 0, $rtime[IDX_MONTH], $rtime[IDX_DAY], $rtime[IDX_YEAR]);            // OK, these three nested loops are responsible for finding the date...            //            // The class has 2 limitations/bugs right now:            //            // -> it doesn't work for dates in 2036 or later!            // -> it will most likely fail if you search for a Feburary, 29th with a given weekday            //    (this does happen because the class only searches in the next/last 10 years! And            //    while it usually takes less than 10 years for a "normal" date to iterate through            //    all weekdays, it can take 20+ years for Feb, 29th to iterate through all weekdays!            for ($nyear = $rtime[IDX_YEAR]; (($next) ? ($nyear = $rtime[IDX_YEAR] - 10)); $nyear = $nyear + (($next) ? 1 : -1)) {               foreach ($cron[IDX_MONTH] as $nmonth) {                  foreach ($cron[IDX_DAY] as $nday) {                     if (checkdate($nmonth, $nday, $nyear)) {                        $ndate = mktime(0, 0, 1, $nmonth, $nday, $nyear);                        if (($next) ? ($ndate >= $cdate) : ($ndate  minute    *    [1]    -> hour    *    [2]    -> day    *    [3]    -> month    *    [4]    -> weekday    *    [5]    -> year    *    * The array is used by various functions.    *    * @access    private    * @param    int $timestamp If none is given, the current time is used    * @return    mixed    */   static private function getTimestamp($timestamp = null)   {      if (is_null($timestamp)) {         $arr = explode(',', strftime('%M,%H,%d,%m,%w,%Y', time()));      } else {         $arr = explode(',', strftime('%M,%H,%d,%m,%w,%Y', $timestamp));      }      // Remove leading zeros (or we'll get in trouble ;-)      foreach ($arr as $key => $value) {         $arr[$key] = (int)ltrim($value, '0');      }      return $arr;   }   /**    * findValue() checks if the given value exists in an array. If it does not exist, the next    * higher/lower value is returned (depending on $next). If no higher/lower value exists,    * false is returned.    *    * @access    public    * @param    int $value    * @param    mixed $data    * @param    bool $next    * @return    mixed    */   static private function findValue($value, $data, $next = true)   {      if (in_array($value, $data)) {         return (int)$value;      } else {         if (($next) ? ($value = end($data))) {            foreach ($data as $curval) {               if (($next) ? ($value <= (int)$curval) : ($curval  $value) {         $cron[$key] = array_reverse($value);      }      return $cron;   }}

tdcron_entry.php

<?php/** * tinyCronEntry is part of tdCron. Its a class to parse Cron-Expressions like "1-45 1,2,3 1-30/5 January,February Mon,Tue" * and convert it to an easily useable format. * * The parser is quite powerful and understands pretty much everything you will ever find in a Cron-Expression. * * A Cron-Expression consists of 5 segments: * * 
 *  .---------------- minute (0 - 59) *  |   .------------- hour (0 - 23) *  |   |   .---------- day of month (1 - 31) *  |   |   |   .------- month (1 - 12) *  |   |   |   |  .----- day of week (0 - 6) *  |   |   |   |  | *  *   *   *   *  * * 

* * Each segment can contain values, ranges and intervals. A range is always written as "value1-value2" and * intervals as "value1/value2". * * Of course each segment can contain multiple values seperated by commas. * * Some valid examples: * *

 * 1,2,3,4,5 * 1-5 * 10-20/* * Jan,Feb,Oct * Monday-Friday * 1-10,15,20,40-50/2 * 

* * The current version of the parser understands all weekdays and month names in german and english! * * Usually you won't need to call this class directly. * * Copyright (c) 2010 Christian Land / tagdocs.de * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Christian Land * @package tinyCron * @subpackage tinyCronEntry * @copyright Copyright (c) 2010, Christian Land / tagdocs.de * @version v0.0.1 beta */class tdCronEntry{ /** * The parsed cron-expression. * @var mixed */ static private $cron = array(); /** * Ranges. * @var mixed */ static private $ranges = array( IDX_MINUTE => array('min' => 0, 'max' => 59), // Minutes IDX_HOUR => array('min' => 0, 'max' => 23), // Hours IDX_DAY => array('min' => 1, 'max' => 31), // Days IDX_MONTH => array('min' => 1, 'max' => 12), // Months IDX_WEEKDAY => array('min' => 0, 'max' => 7) // Weekdays ); /** * Named intervals. * @var mixed */ static private $intervals = array( '@yearly' => '0 0 1 1 *', '@annually' => '0 0 1 1 *', '@monthly' => '0 0 1 * *', '@weekly' => '0 0 * * 0', '@midnight' => '0 0 * * *', '@daily' => '0 0 * * *', '@hourly' => '0 * * * *' ); /** * Possible keywords for months/weekdays. * @var mixed */ static private $keywords = array( IDX_MONTH => array( '/(january|januar|jan)/i' => 1, '/(february|februar|feb)/i' => 2, '/(march|maerz|m?rz|mar|mae|m?r)/i' => 3, '/(april|apr)/i' => 4, '/(may|mai)/i' => 5, '/(june|juni|jun)/i' => 6, '/(july|juli|jul)/i' => 7, '/(august|aug)/i' => 8, '/(september|sep)/i' => 9, '/(october|oktober|okt|oct)/i' => 10, '/(november|nov)/i' => 11, '/(december|dezember|dec|dez)/i' => 12 ), IDX_WEEKDAY => array( '/(sunday|sonntag|sun|son|su|so)/i' => 0, '/(monday|montag|mon|mo)/i' => 1, '/(tuesday|dienstag|die|tue|tu|di)/i' => 2, '/(wednesdays|mittwoch|mit|wed|we|mi)/i' => 3, '/(thursday|donnerstag|don|thu|th|do)/i' => 4, '/(friday|freitag|fre|fri|fr)/i' => 5, '/(saturday|samstag|sam|sat|sa)/i' => 6 ) ); /** * parseExpression() analyses crontab-expressions like "* * 1,2,3 * mon,tue" and returns an array * containing all values. If it can't be parsed, an exception is thrown. * * @access public * @param string $expression The cron-expression to parse. * @return mixed * @throws Exception */ static public function parse($expression) { $dummy = array(); // Convert named expressions if neccessary if (substr($expression, 0, 1) == '@') { $expression = strtr($expression, self::$intervals); if (substr($expression, 0, 1) == '@') { // Oops... unknown named interval!?!! throw new Exception('Unknown named interval [' . $expression . ']', 10000); } } // Next basic check... do we have 5 segments? $cron = explode(' ', $expression); if (count($cron) 5) { // No... we haven't... throw new Exception('Wrong number of segments in expression. Expected: 5, Found: ' . count($cron), 10001); } else { // Yup, 5 segments... lets see if we can work with them foreach ($cron as $idx => $segment) { try { $dummy[$idx] = self::expandSegment($idx, $segment); } catch (Exception $e) { throw $e; } } } return $dummy; } /** * expandSegment() analyses a single segment * * @access public * @param $idx * @param $segment * @return array * @throws Exception */ static private function expandSegment($idx, $segment) { // Store original segment for later use $osegment = $segment; // Replace months/weekdays like "January", "February", etc. with numbers if (isset(self::$keywords[$idx])) { $segment = preg_replace(array_keys(self::$keywords[$idx]), array_values(self::$keywords[$idx]), $segment); } // Replace wildcards if (substr($segment, 0, 1) == '*') { $segment = preg_replace('/^*(/d+)?$/i', self::$ranges[$idx]['min'] . '-' . self::$ranges[$idx]['max'] . '$1', $segment); } // Make sure that nothing unparsed is left :) $dummy = preg_replace('/[0-9-/,]/', '', $segment); if (!empty($dummy)) { // Ohoh.... thats not good :-) throw new Exception('Failed to parse segment: ' . $osegment, 10002); } // At this point our string should be OK - lets convert it to an array $result = array(); $atoms = explode(',', $segment); foreach ($atoms as $curatom) { $result = array_merge($result, self::parseAtom($curatom)); } // Get rid of duplicates and sort the array $result = array_unique($result); sort($result); // Check for invalid values if ($idx == IDX_WEEKDAY) { if (end($result) == 7) { if (reset($result) 0) { array_unshift($result, 0); } array_pop($result); } } foreach ($result as $key => $value) { if (($value self::$ranges[$idx]['max'])) { throw new Exception('Failed to parse segment, invalid value [' . $value . ']: ' . $osegment, 10003); } } return $result; } /** * parseAtom() analyses a single segment * * @access public * @param string $atom The segment to parse * @return array */ static private function parseAtom($atom) { $expanded = array(); if (preg_match('/^(d+)-(d+)(/(d+))?/i', $atom, $matches)) { $low = $matches[1]; $high = $matches[2]; if ($low > $high) { list($low, $high) = array($high, $low); } $step = isset($matches[4]) ? $matches[4] : 1; for ($i = $low; $i <= $high; $i += $step) { $expanded[] = (int)$i; } } else { $expanded[] = (int)$atom; } $expanded2 = array_unique($expanded); return $expanded; }}

推荐教程:《TP5》

以上就是THINKPHP的cron任务实现的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/89754.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
36漫画首页免费登录入口大厅 36漫画登录在线免费观看平台
上一篇 2025年11月18日 06:55:45
科幻题材回合制游戏《威赫战线》将于2026年2月5日登陆PC端 免费试玩版现已发布!
下一篇 2025年11月18日 06:57:47

相关推荐

  • PHP三元运算符和if如何选_PHP三元运算符与if选择指南

    三元运算符适用于简单赋值或返回值,如条件赋值、模板输出;if语句适合复杂逻辑、多分支或多操作场景。性能差异可忽略,应优先考虑可读性和维护性。两者可结合使用,分工明确更清晰。 在PHP开发中,三元运算符和if语句都能实现条件判断,但它们适用的场景不同。选择合适的方式能让代码更清晰、易维护。关键不是“哪…

    2026年9月23日
    100
  • VSCode配置MacOS C环境 详细图解VSCode搭建C++开发

    在mac++os上用vscode配置c/c++环境的关键是安装xcode command line tools以获取clang编译器和lldb调试器,然后安装vscode的c/c++扩展,接着创建项目文件夹和源文件,通过配置tasks.json定义编译任务,确保使用clang编译当前文件并生成可执行…

    2026年9月23日
    100
  • php数据如何防止CSRF跨站请求伪造_php数据表单令牌安全机制

    防止CSRF的核心是验证请求来源合法性,常用方法为表单令牌机制。1. 生成并存储CSRF令牌:用户访问表单页面时,PHP使用session_start()开启会话,通过bin2hex(random_bytes(32))生成安全令牌,存入$_SESSION[‘csrf_token&#821…

    2026年9月23日
    000
  • QQ阅读电子书官网_QQ阅读官方下载地址

    QQ阅读电子书官网是yuedu.reader.qq.com,该网站提供小说、杂志、漫画等多种数字内容,支持多设备同步与个性化阅读设置。 QQ阅读电子书官网地址在哪里?这是不少网友都关注的,接下来由PHP小编为大家带来QQ阅读电子书官网,感兴趣的网友一起随小编来瞧瞧吧! https://yuedu.3…

    2026年9月23日
    000
  • Snagit的AI工具怎么裁剪图片?教你精准完成图片裁剪方法

    Snagit的AI工具怎么裁剪图片?教你精准完成图片裁剪方法Snagit的AI工具怎么裁剪图片?教你精准完成图片裁剪方法Snagit的AI工具怎么裁剪图片?教你精准完成图片裁剪方法Snagit的AI工具怎么裁剪图片?教你精准完成图片裁剪方法

    Snagit虽无一键AI裁剪,但通过魔棒、智能移动等智能工具辅助选区,结合裁剪功能可高效精准裁剪;关键在于利用颜色识别与对象分离技术提升效率,避免纯手动操作,再通过调整比例、放大细节、善用撤销等功能优化结果。 ☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R…

    2026年9月23日 用户投稿
    000
  • Java javac 命令与当前工作目录解析

    在Java编译环境中,javac命令的“当前目录”指的是命令被执行的物理位置,而非源文件所在的目录。理解这一概念对于正确配置和管理Java项目的编译路径至关重要,特别是当默认的classpath设置为.时,它决定了编译器查找类文件的起点。 1. javac 命令与当前工作目录的定义 在操作系统中,当…

    2026年9月23日
    100
  • 苹果 iPhone Air 今日正式发售:仅支持 eSIM,起售价 7999 元

    10 月 22 日消息,苹果全新 iphone air 于今日上午 8:00 正式开售,起售价定为 7999 元。值得关注的是,该机型仅支持 esim 功能,用户需持本人有效身份证件前往运营商实体营业厅完成实名核验与服务激活。现阶段仍处于商用试验阶段,暂未开放线上办理通道。 iPhone Air 搭…

    2026年9月23日
    200
  • VSCode调试JavaScript代码(详细图解,前端必学技能)

    掌握VSCode调试JavaScript需先安装Node.js和VSCode,创建项目及app.js文件后,配置launch.json,设置断点并启动调试,通过变量面板和控制台检查值,结合条件断点、日志点、监听表达式等技巧提升效率;调试浏览器代码需安装Chrome或Edge调试插件,配置url和we…

    2026年9月23日
    200
  • 配置php递归函数处理递归转换_通过php递归函数转换数据格式

    递归函数通过自我调用处理树形结构,需有终止条件和问题缩小机制;示例中将扁平数组按parent_id构建为嵌套树,反之亦可展平为带层级的列表,适用于菜单、分类等无限级数据操作。 在PHP开发中,经常需要处理树形结构数据,比如分类、菜单、评论嵌套等。这类数据通常具有父子关系,且层级不确定,这时就需要使用…

    2026年9月23日
    100
  • Bash Shell 中单引号和双引号的区别

    Bash Shell 中单引号和双引号的区别Bash Shell 中单引号和双引号的区别Bash Shell 中单引号和双引号的区别Bash Shell 中单引号和双引号的区别

    在 linux 命令行中,引号是处理文件名中的空格和特殊字符的常用工具。引号在 shell 脚本中具有“特殊功能”,可能让初学者感到困惑。让我们详细探讨不同类型的引号字符及其在 shell 脚本中的用法。 有四种不同类型的引号字符: 单引号 ‘双引号 “反斜杠 反引号 ` 除…

    2026年9月23日 用户投稿
    500
  • UC浏览器官方网页版登录入口 UC浏览器最新官网链接

    UC浏览器官方网页版登录入口在官网https://www.ucweb.com/,点击顶部“网页版”选项并登录账号即可使用。 UC浏览器官方网页版登录入口在哪里?这是不少网友都关注的,接下来由PHP小编为大家带来UC浏览器最新官网链接,想了解UC浏览器功能特点的网友一起随小编来瞧瞧吧! https:/…

    2026年9月23日
    700
  • Linux中如何查看服务日志?journalctl与syslog使用指南

    Linux中如何查看服务日志?journalctl与syslog使用指南Linux中如何查看服务日志?journalctl与syslog使用指南Linux中如何查看服务日志?journalctl与syslog使用指南Linux中如何查看服务日志?journalctl与syslog使用指南

    排查linux服务问题时,首选journalctl或syslog类系统查看日志。journalctl适用于systemd系统,可查看内核消息、服务启动输出等,支持按时间、单元、优先级过滤;syslog适用于传统系统,需服务主动发送日志,支持集中管理。掌握两者使用能有效定位问题。 在Linux系统中排…

    2026年9月23日 用户投稿
    100
  • Java语法基础中main方法为什么必须是public static void

    Main方法必须声明为public static void以确保JVM能无访问限制地通过类名直接调用,且不依赖对象实例或返回值,符合JVM规范对程序入口的强制要求。 Main方法是Java程序的入口点,它的标准声明形式为:public static void main(String[] args)。…

    2026年9月23日
    200
  • ElevenLabs的AI混合工具怎么用?生成逼真语音的详细操作教程

    ElevenLabs的AI混合工具核心在于VoiceLab功能,结合Voice Design与Instant Voice Cloning实现声音的精细调控与克隆。通过参数调整和高质量音频输入,用户可从零设计或克隆声音,并经反复迭代优化情感表达与自然度。其优势在于对声音细节的精准控制、克隆的真实感及灵…

    2026年9月23日
    100
  • 优化 Laravel Nova 动作响应消息的持久性与交互性

    本文探讨了 Laravel Nova 动作响应消息(toast 提示)持续时间过短的问题,尤其对于耗时较长的操作,默认提示难以满足用户反馈需求。我们提出并详细介绍了如何利用 Laravel Nova 4 的通知功能,实现持久化且可交互的用户通知,从而有效解决传统 toast 消息的局限性,提升用户体…

    2026年9月23日
    400
  • 如何在mysql中配置用户连接权限

    创建用户并设置密码:使用CREATE USER指定主机和密码,如’localhost’或’%’(存在安全风险);2. 授予权限:通过GRANT赋予ALL、SELECT等操作权限,并用FLUSH PRIVILEGES生效;3. 验证管理:用SHOW GR…

    2026年9月23日
    900
  • Reflection AI 完成 20 亿美元融资,打造“开放智能”

    美国人工智能初创企业 reflection ai 宣布成功募集 20 亿美元资金,其中英伟达领衔投资 8 亿美元,推动公司估值跃升至 80 亿美元。这家成立仅一年的科技新星,致力于打造“人人可及的前沿开放智能(open intelligence)”。 Reflection AI 表示,已集结一支由顶…

    2026年9月23日
    500
  • mysql安装完如何优化 mysql基础性能调优配置建议

    mysql安装完如何优化 mysql基础性能调优配置建议mysql安装完如何优化 mysql基础性能调优配置建议mysql安装完如何优化 mysql基础性能调优配置建议mysql安装完如何优化 mysql基础性能调优配置建议

    安装完 mysql 后需进行基础配置调优以提升性能,主要包括以下五点:1. 设置 innodb_buffer_pool_size 为物理内存的50%~80%,如16g内存可设为12g;2. 调整 max_connections 至合理并发数如500,并设置 wait_timeout 和 intera…

    2026年9月23日 用户投稿
    400
  • [272]如何把Python脚本导出为exe程序

    [272]如何把Python脚本导出为exe程序[272]如何把Python脚本导出为exe程序[272]如何把Python脚本导出为exe程序[272]如何把Python脚本导出为exe程序

    文章目录:一. PyInstaller简介二. PyInstaller在Windows下的安装三. 打包四. 小实例(Windows下) 附加:pyinstaller简介 PyInstaller能够将Python脚本打包成可执行程序,使得在没有Python环境的机器上也可以运行这些程序。 PyIns…

    2026年9月23日 用户投稿
    100
  • PHP数组中内嵌JSON字符串值的解析与访问教程

    本教程详细介绍了如何在PHP中高效地解析和访问包含JSON格式字符串的数组元素。通过使用json_decode()函数,可以将这些JSON字符串转换为可操作的PHP数组或对象,从而轻松提取所需的shortname和fullname等字段值,并提供了遍历和直接访问的示例代码及注意事项。 在php开发中…

    2026年9月23日
    100

发表回复

登录后才能评论
关注微信