17

In an app I'm creating a user is given the possibility to schedule a repeating task. Simply the values for generating the interval schema are:

Minute: [0-59, 90 (each minute)]
Hour: [0-23, 90 (each hour)]
Day of month: [1-31, 90 (each day of month), 91 (last day of month)]
Month: [1-12, 90 (each month)]

So, for example I've got this format: 10 - 2 - 90 - 90 which translates to 2015-07-16 2:10. The method determining the next run time date is able to present me this date. But, I'm looking for the efficient way to check if the next run time date has already passed (easy part) but then generate the first next run time date again. In this case it would be 2015-07-17 2:10.

I've found out that our brain is easily up to the task but I'm unsure which logical steps to follow to determine this in the most efficient way (without writing out all posibilities that is).

Any suggestions?

2

7 Answers 7

10

It is working fine. I am using PHP Cron Parser. It has everything that we needed.

Or else, you could use Cron Expression easier and more efficient. Some reference answers are already here and here in Stack Overflow.

For Cron Expression, you could use:

$cron = Cron\CronExpression::factory('@daily');
$cron->isDue();
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');//this give next run date.
//echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s');//this give previous run date.

And this is exactly the same what you have and Cron Expression also have,

enter image description here

All what you need to do is, just use PHP Cron Expression. Hope this helps.

2
  • Thanks for your answer but maybe my question is unclear? I'm looking for the way (programmatically) to solve this issue given the structure in the question.
    – Ben
    Commented Jul 28, 2015 at 10:58
  • For cron expression, You could use like this, $cron->getNextRunDate()->format('Y-m-d H:i:s'); $cron->getPreviousRunDate()->format('Y-m-d H:i:s'); It is mentioned under Usage in this link, github.com/mtdowling/cron-expression
    – alagu
    Commented Jul 28, 2015 at 11:20
8
+100

This is nearly Cron syntax, so why creating something own which does exactly the same job?

It should be pretty easy to switch to a valid cron syntax and use a simple library for parsing, etc.

An example would be https://github.com/mtdowling/cron-expression where you could get the next run date for free:

$cron->getNextRunDate()->format('Y-m-d H:i:s');

You would also have the possibility to use values like 0/15 to run every 15 minutes, etc. Another benefit is, that cron syntax is common knowledge which prevents misinterpretation of the format.

2
  • This looks useful. Only downside will be that I've to rewrite some parts, but I think that's not to much of a hassle. I'll check out the function that determines the next run date first and see if I can come up with something similar to that.
    – Ben
    Commented Jul 22, 2015 at 8:47
  • While it was not exactly what I was looking for originally you were the first to come up with this library. Thanks for helping me out.
    – Ben
    Commented Jul 29, 2015 at 8:07
6

I've assumed the interval of this is daily. If not you can adjust the strtotime line.

You'll want to turn the date into a timestamp, and then add one day onto it. PHP makes that pretty easy.

Assuming you've already got the date parsed into international format of 2015-07-17 2:10, you can do the following:

$date = '2015-07-17 2:10'; // Parsed date
$timestamp = strtotime($date);
if($timestamp > time()){
    // Date hasn't hit yet
} else {
    $next_run = strtotime("+1 day", $timestamp);
}
3
  • In this case you're right, but the trick lies in the addition of time. Some cases 1 day, 10 minutes, next month. Is has to be determined someway.
    – Ben
    Commented Jul 22, 2015 at 8:41
  • Ah I see, so the problem isn't calculating the next time to run, the problem is working out what the interval is? In that case my answer doesn't help much
    – Mike
    Commented Jul 22, 2015 at 8:51
  • No problem, thanks for helping out! I need the "next run time" date so I can list it in a status list.
    – Ben
    Commented Jul 22, 2015 at 8:55
6

Check out https://github.com/fightbulc/moment.php, it offers the possibility to add/substract seconds, minutes, hours, month and years. For example (taken from the github demo site):

$m = new \Moment\Moment('2012-05-15T12:30:00', 'CET');
echo $m->addHours(2)->format(); // 2012-05-15T14:30:00+0200

$m = new \Moment\Moment('2012-05-15T12:30:00', 'CET');
echo $m->subtractDays(7)->subtractMinutes(15)->format(); //  2012-05-08T12:15:00+0200
2
  • I will take a look at this and see if it's useful. Thanks!
    – Ben
    Commented Jul 22, 2015 at 8:41
  • The problem doesn't lie in the functionality to add a specific amount of time but to determine the next run time based on the intervalschema given. This however is a nice library, but not what I'm after to solve the case.
    – Ben
    Commented Jul 22, 2015 at 8:44
5

Why worry about if it has run, or when its next run time is?

Could you just run a script every minute, checking for all matching jobs, then executing them?

Shouldn't be a big problem writing a SQL query that matches all possibilities for a certain point in time :)

5
  • The next run time is used to display in a status list. The script is running every minute ;)
    – Ben
    Commented Jul 22, 2015 at 8:39
  • Do you need to store it in the backend, or just give the list of cronjobs and let javascript calculate it and show it to the user?
    – Richard87
    Commented Jul 22, 2015 at 8:51
  • I don't need to store it but calculate it on the fly. The script runs every minute and I can check if the "next run date" has passed already but then I need to next "next run date" to display on the screen (it's a status board where the user can see when a task will be performed again)
    – Ben
    Commented Jul 22, 2015 at 8:58
  • Well, thats easy to update view javasript, I would also add a logging table, where all processes is logged when it is started, and how long it took to complete, then you could check if your job has started jet, how long it has been running etc by simple ajax calls
    – Richard87
    Commented Jul 22, 2015 at 9:02
  • True, but in essence that's not what I'm after. I'm still facing the reason of this question. How to effectively and efficiently determine the next run time with the given variables (which of course vary from job to job) date when the run time date for today has already passed.
    – Ben
    Commented Jul 22, 2015 at 9:14
5

You could simply use the native DateTime classe.

$timeString = '2015-07-16 2:10';
$date = DateTime::createFromFormat('Y-m-d H:i', $timeString);
$date->modify('+1 day');

$now = new DateTime();

if ($date > $now) {
    // The date is in the future
} else {
    // The date is today, or is in the past
}

But if you need a real cron syntax, the answer by @echox is much better.

1
  • I'm aware of these possibilities but that's not what I'm looking for. I'm looking for the way to determine the next runtime if a cron job task for today has already passed. In some cases it might be the next day, other case the next minute, or next hour, or last day of next month and so on. This answer wasn't helping me out, but maybe it will help someone else in the future.
    – Ben
    Commented Jul 28, 2015 at 10:56
2

To be honest I wasn't quite satisfied with the accepted and rewarded answer because I wanted to figure it out myself, not ending up with an external library and rewrite my code.

Given my cron like syntax as described in the question I've created a function to determine the next run time. I'd like to share it with the intention to help out others in the future if you're facing a similar problem. Maybe it points you into the direction you need.

Some demo cases

$cases = [
    // Every minute
    ['i' => 90, 'H' => 90, 'd' => 90, 'm' => 90],
    // Every 5th minute
    ['i' => 5, 'H' => 90, 'd' => 90, 'm' => 90],
    // Every day at 02:15
    ['i' => 15, 'H' => 2, 'd' => 90, 'm' => 90],
    // Every last day of the month at 15:20
    ['i' => 20, 'H' => 15, 'd' => 91, 'm' => 90],
    // June 4th at 12:37
    ['i' => 37, 'H' => 12, 'd' => 4, 'm' => 6],
    // Every minute between 04:00 and 05:00 at every day in October
    ['i' => 90, 'H' => 4, 'd' => 90, 'm' => 10],
];

Function:

function getNextRunTime($config) {
    $minute = $config['i'];
    $hour   = $config['H'];
    $day    = $config['d'];
    $month  = $config['m'];

    // Get minute
    switch($minute) {
        case 90 :
            $nextMinute = date('i', strtotime('now + 1 minute'));
            break;
        default :
            $nextMinute = $minute;
    }

    // Get hour
    switch($hour) {
        case 90 :
            if($minute == 90 || $nextMinute > date('i')) {
                $nextHour = date('H');
            } else {
                $nextHour = date('H', strtotime('now + 1 hour'));
            }
            break;
        default :
            $nextHour = $hour;
    }

    // Get day
    switch($day) {
        case 90 :
            if($hour == 90 && $nextHour > date('H')) {
                $nextDay = date('d');
            } elseif($hour <> 90 && $nextHour <= date('H')) {
                $nextDay = date('d', strtotime('now + 1 day'));
            } else {
                if($nextHour > date('H')) {
                    $nextDay = date('d');
                } else {
                    if ($nextMinute > date('i')) {
                        $nextDay = date('d');
                    } else {
                        $nextDay = date('d', strtotime('now + 1 day'));
                    }
                }
            }
            break;
        case 91 :
            if(date('t') == date('d')) {
                if($nextHour > date('H')) {
                    $nextDay = date('d');
                } elseif($nextHour == date('H') && $nextMinute > date('i')) {
                    $nextDay = date('d');
                } else {
                    $nextDay = date('t', strtotime('now + 1 month'));
                }
            } else {
                $nextDay = date('t');
            }
            break;
        default :
            $nextDay = $day;
    }

    // Get month
    switch($month) {
        case 90 :
            if($day == 90 || $nextDay > date('d')) {
                $nextMonth = date('m');
            } elseif($nextDay == date('d')) {
                if($hour == 90 || $nextHour > date('H')) {
                    $nextMonth = date('m');
                } elseif($nextHour == date('H')) {
                    if($minute == 90 || $nextMinute > date('i')) {
                        $nextMonth = date('m');
                    } else {
                        $nextMonth = date('m', strtotime('now + 1 month'));
                    }
                } else {
                    $nextMonth = date('m', strtotime('now + 1 month'));
                }
            } else {
                $nextMonth = date('m', strtotime('now + 1 month'));
            }
            break;
        default :
            $nextMonth = $month;
    }

    // Get year
    if($month == 90 || $nextMonth > date('m')) {
        $nextYear = date('Y');
    } elseif($nextMonth == date('m')) {
        if($day == 90 || $nextDay > date('d')) {
            $nextYear = date('Y');
        } elseif($nextDay == date('m')) {
            if($hour == 90 || $nextHour > date('H')) {
                $nextYear = date('Y');
            } elseif($nextHour == date('H')) {
                if($minute == 90 || $nextMinute > date('i')) {
                    $nextYear = date('Y');
                } else {
                    $nextYear = date('Y') + 1;
                }
            } else {
                $nextYear = date('Y') + 1;
            }
        } else {
            $nextYear = date('Y') + 1;
        }
    } else {
        $nextYear = date('Y') + 1;
    }

    // Create the timestamp for the 'Next Run Time'
    $nextRunTime = mktime($nextHour, $nextMinute, 0, $nextMonth, $nextDay, $nextYear);

    // Check if the job has to run every minute, maybe a reset to d-m-Y h:00 is possible
    if($nextRunTime > time() && $minute == 90) {
        $tempNextRunTime = mktime($nextHour, 0, 0, $nextMonth, $nextDay, $nextYear);

        if($tempNextRunTime > time()) {
            $nextMinute  = 0;
            $nextRunTime = $tempNextRunTime;
        }
    }

    // Check if the job has to run every hour, maybe a reset to d-m-Y 00:i is possible
    if($nextRunTime > time() && $hour == 90) {
        $tempNextRunTime = mktime(0, $nextMinute, 0, $nextMonth, $nextDay, $nextYear);

        if($tempNextRunTime > time()) {
            $nextHour    = 0;
            $nextRunTime = $tempNextRunTime;
        }
    }

    // Check if the job has to run every day, maybe a reset to 1-m-Y H:i is possible
    if($nextRunTime > time() && $day == 90) {
        $tempNextRunTime = mktime($nextHour, $nextMinute, 0, $nextMonth, 1, $nextYear);

        if($tempNextRunTime > time()) {
            $nextRunTime = $tempNextRunTime;
        }
    }

    // Return the Next Run Time timestamp
    return $nextRunTime;
}

Output (execution time 23-09-2015, 11:12):

string '23-09-2015, 11:13' (length=17)
string '23-09-2015, 12:05' (length=17)
string '24-09-2015, 02:15' (length=17)
string '30-09-2015, 15:20' (length=17)
string '04-06-2016, 12:37' (length=17)
string '01-10-2015, 04:00' (length=17)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.