PHP中计算cron下次运行时间

2024-01-11

我正在我自己的个人框架中设计一个任务调度程序,并试图避免不那么灵活的“运行每个n分钟/小时/天”的方法会更容易实现。我想做的是模仿 cron 调度。我有适当的函数来分割模式并计算下一个日期(一个月中的某一天)的下一个值)目前,但如果有比我正在做的事情更容易的事情,或者可能有更好的方法来做我想做的事情,我不想继续前进。

/**
  * Takes pattern(s) for various time attributes and calculates the next time the task should run
  *
  * @param mixed $minute Pattern or value of minute: 0-59 or 15,45 or * or * /5 (every 5 minutes)
  * @param mixed $hour Pattern or value of hour: 0-23 or 0,6,12 or * or * /2 (every 2 hours)
  * @param mixed $date Pattern or value of date: 1-31 or 1,15 or * or * /5 (every 5 days)
  * @param mixed $day Pattern or value of weekday: 0-7 or 0,1,7 or * or * /7 (every 7 days) - takes precedence over date
  * @return string Timestamp of next run time
  */
 public static function calcNextRun( $minute, $hour, $date, $day )
 {
  # Simplest first, if all * then we run every minute. Return timestamp for next whole minute
  if ( $minute == '*' && $hour == '*' && $date == '*' && $day == '*' )
   return mktime( date( "H" ), date( "i" ), 0 ) + 60; # Prettier than time() + 60, isn't that reason enough?

  # Default to current values
  $nextDate = date( "d" );
  $nextMonth = date( "m" );
  $nextYear = date( "Y" );
  $nextDay = date( "N" );
  $nextHour = date( "H" );
  $nextMinute = date( "i" );

  # Calculate month date to run on, using multiple dates in the presence of , or -
  if( strstr( $date, ',' ) || strstr( $date, '-' ) )
  {
   # Variable to determine whether the date has been set or not
   $dateSet = false;

   # Determine if there's a range in thurr
   $rangeExists = ( strstr( $date, '-' ) ) ? true : false ;

   # Set up the $dates array, exploding if multiple values is present
   $dates = array();
   if ( strstr( $date, ',' ) )
    $dates = explode( ',', $date );
   else
    $dates[] = $date;

   # If we have a range(s) present then we expand them into full stuffs
   foreach ( $dates as $key => $val )
    if ( strstr( $val, '-' ) )
     $dates = array_merge( $dates, self::expandRange( $val ) ); # Merge the expanded range into the $dates array

   # Loop through the $dates array and remove any lingering ranges
   foreach ( $dates as $key => $val )
    if ( strstr( $val, '-' ) )
     unset( $dates[ $key ] );

   # Sort the array
   sort( $dates );

   # Determine the next lowest value
   foreach( $dates as $val )
   {
    # If the value is higher than the maximum number of dates this month, lower it to that
    if ( $val > date( "t" ) )
     $val = date( "t" );

    # If $val is higher than today's date, we use that
    if ( $val > date( "d" ) )
    {
     $nextDate = $val;
     $dateSet = true;
     break; # We're done, we have our value
    }
   }

   # If the date has not been set, add one to the month and use the lowest value in the array
   if ( !$dateSet )
   {
    # Increment the month. Maybe the year. Hurr hurr
    if ( $nextMonth == 12 )
    {
     $nextMonth = 1;
     $nextYear++;
    }
    else
     $nextMonth++;

    # Set the next day to the lowest value in the array
    $nextDate = $dates[0];
   }
  }
  elseif ( strstr( $date, '/' ) ) # Every n days
  {
   $parts = explode( '/', $date );
   $numDays = array_pop( $parts );

   # Calculate the timestamp of n days from now
   $nDayTime = time() + ( $numDays * 86400 ); # 86400 seconds in a day

   # Update values of $nextVars
   $nextDate = date( "d", $nDayTime );
   $nextMonth = date( "m", $nDayTime );
   $nextYear = date( "Y", $nDayTime );
   $nextDay = date( "N", $nDayTime );
  }
  elseif ( $date == (int)$date )
  {
   if ( $date < date( "j" ) )
   {
    # Determine if the month pushes into the next year
    if ( $nextMonth == 12 )
    {
     $nextMonth = 1;
     $nextYear++;
    }
    else
     $nextMonth++;
   }

   $nextDate = $date;
  }

  # Return the new timestamp!
  return mktime( $nextHour, $nextMinute, 0, $nextMonth, $nextDate, $nextYear );
 }

 /**
  * Takes a range and returns an array with all values belonging to that range
  *
  * @param string $range Two values split by a hyphen, ie: 1-5, 0-9, etc.
  * @return array Array of values between the two parts of the range
  */
 private static function expandRange( $range )
 {
  # Get the parts of the range
  $range = explode( '-', $range );

  # Sort just in case the range is handed to us backwards. <_<
  sort( $range );

  # Set up our return array
  $returnArray = array();

  # Populate the return array with all values between min and max
  for($i=$range[0];$i<=$range[1];$i++)
   $returnArray[] = $i;

  return $returnArray;
 }

我不介意使用 cron 使用的所有五个参数,但无论哪种方式,我都希望能够轻松计算与提供的模式匹配的下一个时间戳。

有人对实现这一目标有任何建议吗?我正在考虑创建一个函数,该函数将采用模式(1-7,10,15 或 */5 或 * 或其他)和当前 val(当前分钟、月份中的某一天等)并返回下一个值从匹配或高于当前值的模式中。


我为 PHP 创建了一个 CRON 解析器,可以满足您的调度需求。它支持一切,包括范围增量(3-59/12,*/2)、范围(3-5)、散列(3#2)、一个月的最后一个工作日/一个月的最后一天(5L、L)、最近的工作日到一个月中的给定日期 (15W),以及可选的年份字段。

https://github.com/mtdowling/cron-expression https://github.com/mtdowling/cron-expression

Usage:

<?php

// Works with predefined scheduling definitions
$cron = Cron\CronExpression::factory('@daily');
$cron->isDue();
$cron->getNextRunDate();
$cron->getPreviousRunDate();

// Works with complex expressions
$cron = new Cron\CronExpression::factory('15 2,6-12 */15 1 *');
$cron->getNextRunDate();

计算下一次 cron 作业何时执行 https://stackoverflow.com/questions/321494/calculate-when-a-cron-job-will-be-executed-then-next-time/3453872#3453872

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP中计算cron下次运行时间 的相关文章

  • 在 JQuery ui 自动完成中显示图像

    我有一个带有 JQuery ui 自动完成功能的脚本 可以完美运行 有一个显示用户名字和姓氏的搜索过程 但在我的数据库中 还有用户的图片 我想将其显示在带有名字和姓氏的建议中 数据库中pic包含图片url 剧本 function searc
  • 如何将 JSON 数据从 Android 发送到 php url?

    我想将登录信息从我的应用程序发送到 php url 因为这我的应用程序将崩溃 任何人都可以帮助我解决这个问题 这是我的服务器登录方法 我想将数据发送到此登录方法 Method public method login Parameters 3
  • jquery ajax加载后丢失CSS

    大家知道如何解决 load Ajax 请求后的 css 问题吗 例如 如果我想从网页加载 DIV 在我的 Ajax 请求之后 container load path to div div id 我丢失了与该 div 关联的所有 css 和脚
  • 在 PHP 中设置 HTTP 响应代码(在 Apache 下)

    给出以下两种在 PHP 中设置 HTTP 响应代码的方法 具体来说 在 Apache 下 方法一 http response code 404 方法二 header HTTP 1 0 404 Not Found 我的问题是 除了这个事实之外
  • 如何在PHP中获取div中的所有链接

    我想从另一个网站打开一个页面 并提取一个中的所有链接 href div of class layout 2 2 在此页面中 我如何使用 PHP 来做到这一点 我想复制layout 2 2中的每个链接this https url 网页 这是我
  • 纯旧 PHP 对象 (POPO) 一词的确切含义是什么?

    我想了解一下波波 我搜索了 popo 发现它代表 Plain Old Php Object 但我不确定 Plain Old Php Object 的确切含义 我想知道什么是 popo 以及在哪里使用它 谢谢 普通旧 在此处插入语言 对象是一
  • Composer 无法下载文件

    我正在尝试在命令行上使用作曲家 php composer phar update php composer phar install php composer phar self update php composer phar selfu
  • 将具有值的产品属性添加到 Woocommerce 中的产品

    我正在使用此代码添加自定义属性 attributes array array name gt Size options gt array S L XL XXL position gt 1 visible gt 1 variation gt
  • 从 PHP 生成渐变颜色

    我想知道如何构建一个给出颜色代码和 显示该颜色的渐变 例如 function generate color int colorindex Generate 10 pale colors of this color 请帮我 迈克尔引用的代码相
  • PHPMailer 验证失败

    当我尝试在工作中使用 Windows Server 2012 上的 PHPMailer 来使用 SMTP 发送报告电子邮件时 出现身份验证失败错误 我在域上使用服务器管理员帐户 我非常确定密码是正确的 检查下面的代码 require PHP
  • PHP 的 mb_internal_encoding 实际上是做什么的?

    根据 PHP 网站 http www php net manual en function mb internal encoding php它这样做 coding 是用于 HTTP 输入的字符编码名称 字符编码转换 HTTP输出字符编码 转
  • Oracle Blob 在 PHP 页面中作为 img src

    我有一个网站当前使用文件服务器上的图像 这些图像显示在页面上 用户可以根据需要拖放每个图像 这是使用 jQuery 完成的 图像包含在列表中 每张图片都非常标准 img src network path image png height 8
  • 访问 Magento 购物车和/或结帐中的运费

    请注意 这个问题是关于运费 而不是价格 有一个重要的区别 即运输方式为店主支付的费用是多少 而不是客户支付的费用 The shipping tablerate数据库表包括一个cost字段 该字段填充在Mage Shipping Model
  • Microsoft VS Code:当我尝试启动程序时,出现错误“spawn php ENOENT”

    我正在尝试在 Microsoft VS Code 上运行 PHP 代码 当我单击启动时 唯一发生的事情是调试控制台中出现错误 生成 php ENOENT 为了解决这个问题 我将 XDebug 的 dll 文件放入 ext 文件夹中 我将 p
  • PHP 致命错误:未找到“MongoClient”类

    我有一个使用 Apache 的网站 代码如下 当我尝试访问它时 我在 error log 中收到错误 PHP Fatal Error Class MongoClient not found 以下是可能错误的设置 但我认为没有错误 php i
  • Doctrine2:入门教程“没有要处理的元数据类”

    我已经将本教程的第一部分运行了三遍 到目前为止 在这里或其他地方进行的大量搜索都无法帮助我使其发挥作用 我收到 没有要处理的元数据类 当我尝试时 php vendor bin doctrine orm schema tool update
  • shell_exec 的输出被截断为 100 个字符

    当在 shell 中运行以下命令时 curl F file filename http 192 168 0 1 产生以下输出 Accuracy 0 0 1 classification Accuracy 0 0 1 classificati
  • 使用 PHP 将 SVG 图像转换为 PNG

    我正在开发一个网络项目 该项目涉及动态生成的美国地图 根据一组数据为不同的州着色 这个 SVG 文件为我提供了一张很好的美国空白地图 并且很容易更改每个州的颜色 困难在于 IE 浏览器不支持 SVG 因此为了让我使用 svg 提供的便捷语法
  • 简单的颜色变化

    我正在创建一个用户界面 用户可以在其中更改页面的颜色值 我想要的是获取分配给其背景颜色的值并将其变亮一定程度 我只是想获得一条亮点线 而不必每次都制作新图像 示例 用户将背景颜色设置为 ECECEC 现在我希望某个元素边框变成 F4F4F4
  • 一些基本的 PHP 问题 [已关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我只是有一些基本的 php 问题来加深我对学习的理解 但我找不到简单的答案 我有一个 php ajax 应用程序 它生成 mysql

随机推荐