首页 > 开发 > PHP > 正文

PHP中实现crontab代码分享

2024-05-04 22:38:09
字体:
来源:转载
供稿:网友

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)");

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表