GithubHelp home page GithubHelp logo

mtdowling / cron-expression Goto Github PK

View Code? Open in Web Editor NEW
4.9K 4.9K 333.0 200 KB

CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due

Home Page: http://mtdowling.com/blog/2012/06/03/cron-expressions-in-php/

License: MIT License

PHP 100.00%

cron-expression's People

Contributors

aensley avatar agervais avatar agervaisintouch avatar chentsulin avatar clippit avatar damu112 avatar dermanomann avatar dragonmantank avatar dragooon avatar fruitl00p avatar gohiei avatar grahamcampbell avatar hannesvdvreken avatar j0k3r avatar kingktulu avatar kkirby avatar latenzio avatar laurencei avatar lucasmichot avatar mtdowling avatar neslonso avatar nyholm avatar pborreli avatar pstast avatar rvanlaarhoven avatar sadortun avatar tqmz avatar tucksaun avatar tvlooy avatar znarkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cron-expression's Issues

Wrong Timezone issue

I'm having an issue where the scheduled timestamp is for UTC rather than my system's timezone. I see in the HoursField::increment() method that the timezone is temporarily set to UTC before the incrementing is done. This seems to be resulting in a configuration for UTC instead of the system timezone:

* 7-7 * * *

This schedules for 7am-7pm UTC.

I'll try to play around with the library's code to see if I'm overlooking something obvious, and if I find a fix, I'll submit a pull request.

No way to pass DateTime with custom TimeZone to isDue

In Laravel's scheduler component, we allow the user to specify a Timezone to evaluate the Cron against. However, cron-expression appears to always overwrite the timezone to the current application timezone, allowing no custom timezone to be set.

Is there any way this can be resolved?

More detailed instructions?

Could you please elaborate on the documentation? I've downloaded a zip with some php files in it, but I don't have a directory called /vendor on my machine, and I don't have a .phar file. How do I use this?

Trying to Schedule Specific Day cron jobs

Hey, so when I feed Jobby "{"name":"52-excel-03/12/2014","command":"/usr/local/bin/php auto-excel-prep.php 52","schedule":"44 22 12 03 *","output":"log-excel.txt","enabled":"true"}"

and I get:

[12-Mar-2014 20:42:01 America/Denver] PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message '00 9 is not a valid CRON expression' in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:105
Stack trace:
#0 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(90): Cron\CronExpression->setExpression('00 9 ')
#1 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(78): Cron\CronExpression->__construct('00 9 ', Object(Cron\FieldFactory))
#2 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(180): Cron\CronExpression::factory('00 9 ')
#3 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(67): Jobby\BackgroundJob->shouldRun()
#4 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(304): Jobby\BackgroundJob->run()
#5 {main}

thrown in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php on line 105
[12-Mar-2014 20:42:01 America/Denver] PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message '42 20 is not a valid CRON expression' in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:105
Stack trace:
#0 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(90): Cron\CronExpression->setExpression('42 20 ')
#1 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(78): Cron\CronExpression->__construct('42 20 ', Object(Cron\FieldFactory))
#2 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(180): Cron\CronExpression::factory('42 20 ')
#3 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(67): Jobby\BackgroundJob->shouldRun()
#4 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(304): Jobby\BackgroundJob->run()
#5 {main}

thrown in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php on line 105
[12-Mar-2014 20:42:02 America/Denver] PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message '42 -1 is not a valid CRON expression' in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:105
Stack trace:
#0 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(90): Cron\CronExpression->setExpression('42 -1 ')
#1 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(78): Cron\CronExpression->__construct('42 -1 ', Object(Cron\FieldFactory))
#2 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(180): Cron\CronExpression::factory('42 -1 ')
#3 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(67): Jobby\BackgroundJob->shouldRun()
#4 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(304): Jobby\BackgroundJob->run()
#5 {main}

thrown in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php on line 105
[12-Mar-2014 20:42:02 America/Denver] PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message '42 3 is not a valid CRON expression' in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:105
Stack trace:
#0 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(90): Cron\CronExpression->setExpression('42 3 ')
#1 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(78): Cron\CronExpression->__construct('42 3 ', Object(Cron\FieldFactory))
#2 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(180): Cron\CronExpression::factory('42 3 ')
#3 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(67): Jobby\BackgroundJob->shouldRun()
#4 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(304): Jobby\BackgroundJob->run()
#5 {main}

thrown in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php on line 105
[12-Mar-2014 20:42:02 America/Denver] PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message '42 6 is not a valid CRON expression' in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:105
Stack trace:
#0 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(90): Cron\CronExpression->setExpression('42 6 ')
#1 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(78): Cron\CronExpression->__construct('42 6 ', Object(Cron\FieldFactory))
#2 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(180): Cron\CronExpression::factory('42 6 ')
#3 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(67): Jobby\BackgroundJob->shouldRun()
#4 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(304): Jobby\BackgroundJob->run()
#5 {main}

thrown in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php on line 105

day of week

hello,

day of wek usage of 1/2 does not work. It should be used every 2 weeks but it raises an InvalidArgumentException....
is the use of 1/2 for day of week not recommended?
greets p

New release?

Hi there, this looks awesome and I'm considering using it for piwik but it looks like the last release is a year old (51 commits behind master).

Is that possible to tag a new release?

If it helps getting there faster, here is the changelog:

  • Avoid infinity loop & division by zero #67
  • Fix getRunDate() shouldn't modify currentTime parameter #57
  • Missing anchors in regexp #63
  • Avoid annotation parsing by Doctrine #62
  • Optimization #52
  • Fixed #20 Weekday-Hash for Saturday and Sunday doesn't seem to work #53
  • Different timezone support #48
  • Fixed regexp for day of week #49
  • Set $currentTime as 'now' #36

I kept only the changes meaningful for end-users (e.g. not changes about tests or docs).

timestamp issue

Passing a timestamp to getRunDate, PHP needs the Timezone set if you are not dealing in UTC.

Simple fix, just add the last line below. Fixed all my troubles.

protected function getRunDate($currentTime = null, $nth = 0, $invert = false, $allowCurrentDate = false)
{
    $currentDate = $currentTime instanceof DateTime
        ? $currentTime
        : new DateTime($currentTime ?: 'now');

    $currentDate->setTimezone(new DateTimeZone(date_default_timezone_get()));

"Impossible cron expression" thrown when number of run dates > 16

Even if I set $which<30 I only get 16 results (instead of 30)before I get an error.
Sample code:

<?php
include( './vendor/autoload.php');

    $cron = Cron\CronExpression::factory('0 10-20/2 * * 1-5 *');
    $eventDates = array();
    for ($which = 0; $which<30; $which++) {
        try{
            $nextDateOfEvent = $cron->getRunDate('now', $which)->format('Y-m-d H:i:s');
        }
        catch (RuntimeException $e) {
            //var_dump($e);
            break;
        }
        array_push($eventDates, $nextDateOfEvent);
    }
    var_dump($eventDates);
    exit();

?>

Day vs Weekday Issue

First of all: nice code, thanks for sharing!

On Sun, Feb 19 2012, I tested with '0 14 1 1,4,7,10 1', so each first monday of the months 1,4,7 and 10, at 14:00 a job has to start, and it returned an error.

The next run date for factory('0 14 1 1,4,7,10 1') started on Sun, Feb 19 2012, should have been 'Mon, Apr 02, 2012 14:00:00' and not 'Mon, Oct 01 2012 14:00:00' as returned.

It's a bit strange in itself: first request the first day of the month, than move over to the first monday. But hey, that's cron as we know it.

Thanks in advance & good luck!

Outdated stable version

The last stable version v1.0.4 has at least one bug:
Some expressions not recognized (0 0 1 * *, 0 0 1 1 *). Works fine in master though.
I have a project that has dependency from this package. But I don't want to use dev-master version of your project, because it can be broken in future commits. Can you please release new stable version? Thanks.

Get the Cron Expression from database

// Works with predefined scheduling definitions
$cron = Cron\CronExpression::factory('* * * * *');
$cron->isDue();
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');
echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s');

getMultipleRunDates fails with bigger $total values

This works:

$cron=Cron\CronExpression::factory("0 0 * * *");
$cron->getMultipleRunDates(12, "2008-11-09 00:00:00");

This fails:

$cron=Cron\CronExpression::factory("0 0 * * *");
$cron->getMultipleRunDates(13, "2008-11-09 00:00:00");

with error:

[04-Nov-2014 09:51:22 Europe/Berlin] PHP Fatal error:  Uncaught exception 'RuntimeException' with message 'Impossible CRON expression' in .../mtdowling/cron-expression/src/Cron/CronExpression.php:321
Stack trace:
  #0 .../mtdowling/cron-expression/src/Cron/CronExpression.php(192): Cron\CronExpression->getRunDate('2008-11-09 00:0...', 12, false, false)
  #1 Command line code(1): Cron\CronExpression->getMultipleRunDates(13, '2008-11-09 00:0...')
  #2 {main}
  thrown in .../mtdowling/cron-expression/src/Cron/CronExpression.php on line 321

The same error happens with different values of $total depending on the cron expression.

Bad example in README.md

In the last example titled "Calculate a run date relative to a specific time", the argument passed to getNextRunDate should be a string (since it's later passed to the DateTime constructor). So, just remove the strtotime function.

BTW, thanks a ton for this. I've had a heck of a time writing my own parser.

Issue with cron

Hi ,
I am from India and my Timezone is UTC +5:30

now the problem that arises to me is that assume the cron entry is "25 0 * * *"

the time now say is 2014-05-13 17:19:00
so the next run time is 2014-05-14 00:25:00

in first loop obviously 0 doesn't match with 17 so the 17 is incremented ..
but here is the issue .. as we are converting to UTC and back .. after increment the time changes to .2014-05-13 17:30:00 notice that the minute is now 30 which is greater than 25.

after the increments are as follows
2014-05-13 17:30:00
2014-05-13 18:30:00
2014-05-13 19:30:00
2014-05-13 20:30:00
2014-05-13 21:30:00
2014-05-13 22:30:00
2014-05-13 23:30:00
2014-05-14 00:30:00

And here the cron expression has been completely missed out and the system gets into an infinite loop

for the time being I have removed the covert to UTC and back feature as we don't need to deal with DST

First Sunday each month

Hi

I'm having trouble getting next run dates for "first Sunday of each month".

Minutes, Hours, Day of month, Month, Day of Week
0 12 ? * MON#1 - First Monday each month - Works
0 12 ? * 2#1 - First Tuesday each month - Works
0 12 ? * 5#1 - First Friday each month - Works
0 12 ? * 0#1 - First Sunday each month - Don't work
0 12 ? * SUN#1 - First Sunday each month - Don't work

I'm getting this error:

InvalidArgumentException
Weekday must be a value between 1 and 5. 0 given

What expression do I need to get the first Sunday of each month?

Add support for question marks

Though it's not a big deal to have a * instead of a ?, it threw an exception using my "valid" cron expressions. If I just replace the ?'s with *'s in the expression, your code still works.

Request: Simple validation function

Thank you for this useful library. It's really great. I have a small feature request. Could you add a validateCronExpression() or isValidCronExpression() static function to CronExpression?

The reason I need this is that there will be situations where schedules are created programatically, and I want to make sure an invalid schedule isn't saved for later usage, causing errors on every run.

Right now, I'm doing this to accomplish what I need:

try {
    \Cron\CronExpression::factory($cronExpression);
} catch (\InvalidArgumentException $e) {
    LogUtil::error('Invalid cron expression "' . $cronExpression . '"');
    return false;
}

// $cronExpression is valid. Proceed.

It would be nice if I could do this:

if (!\Cron\CronExpression::isValidCronExpression($cronExpression)) {
    LogUtil::error('Invalid cron expression "' . $cronExpression . '"');
    return false;
} else {
    // $cronExpression is valid. Proceed.
}

It's a very small change as far as the code I write, but I feel like my current solution is a bit ugly and hack-ish since the underlying code might change in how invalid expressions are handled.

Weekday crontab not working correctly.

First off, awesome library. Thanks for all the hard work.

I'm having an issue with the @Weekly cron tab (using both the alias and the actual cron tab of 0 0 * * 0). The issue is that it works fine for looking ahead, but not so much on looking behind.

If I do 0 0 * * 0 for now, the next date is at 2012-09-09 00:00:00, however the previous due date is 2012-03-11 00:00:00. I did some looking in the code and found that if I modify the following file:

DayOfWeekField, line 118 to: $date->setTime(0, 0, 0);

It works fine.

I'm not sure if this is actually the fix or not, or if something is weird with my machine. I ran PHPUnit on the tests (without my modification) and it came back with several errors and fails. Here is a paste bin of the test output: http://pastebin.com/s0MGpBid

Thanks!

Memory leaks with Opcache

In PHP 5.5 with the builtin Opcache enabled for the CLI using the CronExpression causes memory leaks.

opcache.enable_cli = 1

Execute the following script on the command line:

use Cron\CronExpression;

$expression = CronExpression::factory('25 0 1 * *');

while (true) {
    $expression->isDue();

    usleep(100000);
}

The used memory (RSS) will increase rapidly and PHP will eventually throw a fatal error.

Please note that when changing the expression to * * * * * this issue does not occur.

It may very well be an issue with the Opcache, however I haven't been able to pinpoint exactly what is happening here.

Tested on CentOS 6.4 and Mac OS X 10.9.2 with PHP 5.5.10 and PHP 5.5.11

MON#1,MON#3 doesn't validate

In v1.0.3 it was possible to assign multiple days of week to an DayOfWeekField expression with a week of month:

 $this->assertTrue($f->validate('MON#1,MON#3'));

In master, this doesn't validate anymore while it seems to be supported in terms of isDue().

PHP Fatal error:  Uncaught exception 'InvalidArgumentException' with message 'Invalid CRON field value MON#1,MON#3 as position 4' in /home/t/dev/fs/radiorecorder/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:123
Stack trace:
#0 /home/t/dev/fs/radiorecorder/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(105): Cron\CronExpression->setPart(4, 'MON#1,MON#3')
#1 /home/t/dev/fs/radiorecorder/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(84): Cron\CronExpression->setExpression('00 14 * * MON#1...')
#2 /home/t/dev/fs/radiorecorder/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(72): Cron\CronExpression->__construct('00 14 * * MON#1...', Object(Cron\FieldFactory))
#3 /home/t/dev/fs/radiorecorder/record.php(167): Cron\CronExpression::factory('00 14 * * MON#1...')
#4 /home/t/dev/fs/radiorecorder/record.php(45): Radiorecorder\Radiorecorder->parseBroadcasts('/home/t/dev/fs/...')
#5 /home/t/dev/fs/radiorecorder/record.php(382): Radiorecorder\Radiorecorder->__construct()
#6 {main}
  th in /home/t/dev/fs/radiorecorder/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php on line 123

Is that just a matter of fixing the regex in DayOfWeekField::validate(), or for some reason an undesired expression?

Doctrine Annotations issue

i had to add

AnnotationReader::addGlobalIgnoredName('yearly');
AnnotationReader::addGlobalIgnoredName('annually');
AnnotationReader::addGlobalIgnoredName('monthly');
AnnotationReader::addGlobalIgnoredName('weekly');
AnnotationReader::addGlobalIgnoredName('daily');
AnnotationReader::addGlobalIgnoredName('hourly');

to app/autoload.php in Symfony2 to get it work.

Could we remove the @daily, @... from the DocBlock to avoid this?

Expression with increment of ranges not always working as expected

We have the following expression:
0-25/5,40-59/5 4 * * 0 sync content
Which should fire every five minutes on sundays between 4:00 and 5:00 EXCEPT between 4:25 and 4:40 (Don't ask why :))

The problem is that this expression also fires on 4:30 since there appears to be a little error in AbstractField->isInIncrementsOfRanges. It seams that the problem appears when the range starts with a zero (like mine above).

I could fix the issue by changing:

if ($parts[0] == '*' || $parts[0] == 0) {
    return (int) $dateValue % $stepSize == 0;
}

into:

if ($parts[0] == '*' || $parts[0] === '0') {
    return (int) $dateValue % $stepSize == 0;
}

Although I don't fully understand why that second expression is there in the first place.

Crons run at midnight, when they're not supposed to

I use this library as a dependency for the package Dispatcher. Thank you for this library! It has made the implementation of Dispatcher so much easier!

A few of the users of this package are reporting that their crons are running at midnight when the cron expression does not signify this should happen. Here's specific code that determines when something should be run: https://github.com/Indatus/dispatcher/blob/master/src/Indatus/Dispatcher/Drivers/Cron/ScheduleService.php#L34

Here's the issue users are reporting: Indatus/dispatcher#90

I have not yet tried to recreate this, but plan to soon. Have you seen anything like this happen with the cron-expression library?

Weekday-Hash for Saturday and Sunday doesn't seem to work

Hello!

First off, thanks for the great library!!

I wonder why something like "0 22 ? * SUN#1 *" doesn't work, though... in DayOfWeekField:66 it forces weekday to be within [1,5].
Commenting out that part results in a "Impossible CRON expression" later.

Also, I noticed that the test-line "0 0 0 ? 1/2 FRI#2 *" from your blog doesn't work, probably there's an extra 0.

Thanks

cron-expression throws an error when checking an expired cron expression

I have noticed that I get a "Impossible CronExpression" error any time I have a cron expression that has expired or is in the past.

A little background on how we are using cron-expression. We have maintenance schedules which are scheduled via cron expressions, which makes perfect sense as many are recurring on a set schedule. However, there are times when the maintenance schedule is just for a couple of hours early in the morning and it is a one time thing. That is when we start running into issues.

Example: If today's date/time is 1/29/2015 12:00 and we have a cron expression for a maintenance schedule of "* 1-4 29 1 * 2015" we will get a "Impossible CronExpression" error thrown when checking it through the IsDue() method. Which I assume is because that expression represents a time in the past.

For entering a new cronExpression for a time in the past, an error or warning like this makes sense, but not for a cronExpression that, when entered, was/is valid and as time goes it becomes a time in the past. That should not error out I would think. Any ideas as to why this is happening? And how one would go about fixing it?

Any help on this issue would be most appreciated.

Thanks,

  • Barrett-

getNextRunDate for isDue objects

When i run this test :

    public function testNextWithZeroHour()
    {
        $cron = CronExpression::factory('@weekly');
        $nextRun = $cron->getNextRunDate("2008-11-09 08:00:00");
        $this->assertEquals($nextRun, new \DateTime("2008-11-16 00:00:00"));

        $nextRun = $cron->getNextRunDate("2008-11-09 00:00:00");
        $this->assertEquals($nextRun, new \DateTime("2008-11-16 00:00:00"));

    }

The first work but the second return the currentDate and not the real next execution.

How could we get the real next element ?

Thanks in advance
Cédric

Errors when Day of the Week and Day of the Month set

I think there my be a bug when both the Day of the Week and the Day of the Month are specified (See results below)

cron: * * * * * ---------------------------------------------- (OK)
Next Due: 2011-06-15 23:09:00

cron: 0 17 * * * ---------------------------------------------- (OK)
Next Due: 2011-06-16 17:00:00

cron: 0 0 1 1 0 ----------------------------------------------(Should be 2012-01-01 00:00:00)
Next Due: 2249-10-01 00:00:00

cron: 0 0 1 * 0 ----------------------------------------------(Should be 2012-01-01 00:00:00)
Next Due: 2038-10-31 00:00:00

cron: 59 17 5 7 * ----------------------------------------------(OK)
Next Due: 2011-07-05 17:59:00

cron: 00 11 15 6 * ----------------------------------------------(OK)
Next Due: 2012-06-15 11:00:00

cron: 00 11 14 6 * ----------------------------------------------()OK
Next Due: 2012-06-14 11:00:00

I will look into this and see if I can find a solution.

Cron Expression implement with database and CronTab

you talked about you cron expression work with a database where the Cron Schedule is store and Crontab, can you provide an Sample of that. i want to know how make the Cron grab the Cron Schedule from the databse thanks

Validate full cron command (with time and command itself)

Hello,

is it possible to provide, for example, full cron command like:

*       15-23   *       *       *       wget http://example.com

and later, for example I ->getMinutes(); ->getMonth(), ->getCommand() ?

because going threw source I did not find such functionality..

Thank you!

timezone handling

Is there any reason to set the timezone in getRunDate() if a properly configured $curentTime is set?
I need to validate cronlines against different timezones and it would be nice if timezone is only set if the provided $currentTime is null.

Nice code otherwise :)

lowercase weekday not valid

The validate function in the DayOfWeekField.php matches only upper case days of the week and not lower case. This causes the following bug:

0 9 * * mon Not valid
0 9 * * mon, Valid

The second line is valid because the comma is correctly matched by the validate function.

error(?) in synthetic test

hi, i make such a test
$cron = Cron\CronExpression::factory('* * * * *');
$cron->isDue();
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');
echo "
";
echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s');

which return two SAME date for previous and next run.
Ex:
2011-09-02 01:49:00
2011-09-02 01:49:00
I think it something wrong. i know, it too synthetic test, but anyway - somewhere it may leed to errors in main app

PS
And please correct the example in readme -
echo $cron->getNextRunDate();
echo $cron->getPreviousRunDate();

return is datetime object, which cannot be printed as string

PPS just comparing latest version and version from 16 august, i see broken description in factory function in CronExpression.php

16 aug:
* @param FieldFactory $fieldFactory (optional) Field factory to use with
* the expression. Leave NULL to use the default factory.
*
* @return CronExpression
*/
20 aug:
* @param FieldFactory $fieldFactory (optional) Field factory to use
* @return CronExpression
*/

and thank you for this great class. Cheers!

Invalid getNextRunDate()

Hello, I use your code like this :

// create cron expression
$cronEx = CronExpression::factory('* * * * *');
// create last and next run time
$current_date = new DateTime('2011-09-27 10:10:54');
$next_run = $cronEx->getNextRunDate($current_date);

But when this gets executed, $next_run is '2011-09-27 10:10:00' which is wrong, it should actually be '2011-09-27 10:11:00'.

Thank you for this fine class

"Impossible cron expression" thrown on timezones that offsets with minuets

for time zones that have an offset with minuets, an "Impossible cron expression is thrown when calling isDue or getNextRunDate. It appears to happen because the getNextRun date keeps adding hours and then hits a limit in a for loop.

Steps

  1. use the following expression: 0 */5 * * * *
  2. Set time zone to one that has offset with minuets (Asia/Kabul, or Asia/Calcutta)
  3. Call next getNextRunDate(null, 0, true);

Expected

The next run date for the job is returned

Actual

An Exception is thrown with the message "Impossible cron expression"

cant getNextRunDate for a cronjob

see: 13 14 3 2 3 or At 14:13 on the 3rd during every February but only if the event takes place on Wednesdays.

i get 'Impossible CRON expression'

$cron = CronExpression::factory(13 14 3 2 3);
for ($i = 0; $i < 10; $i++) {
    $x = $cron->getNextRunDate(NULL, $i)->format('Y-m-d H:i:s');
    var_dump($x);
}

if $i <= 3 then it executes fine 

also on

$cron = CronExpression::factory('0 0 0 ? 1/2 FRI#2 *');
if ($cron->isDue()) {
    var_dump('isDue');
}

i get Invalid CRON field value ? as position 3

Month/Daynames should be case insensitive

I find using "JAN" or "SUN" a little unusual, usual crons don't care about the case. I usually use "Jan" or "Sun".

Using str_ireplace() instead of strtr() should do the trick, e.g.

$value = str_ireplace( array( "JAN", "FEB", ... ), array( "0", "1", ... ), $value );

Potential issue with getPreviousRunDate() every minute

Hi,

When the following code:

$cron = Cron\CronExpression::factory('* * * * *');
echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s');

is ran at 10:51:20 , the output is 2014-03-19 10:50:00.

Surely if the cron is scheduled to run every minute, the last run time should be 10:51:00?

Regards,

Rhodri

Invalid Cron

I am using a library called Jobby to schedule some cron jobs and it uses your code as a dependancy. I've had the creator of Jobby look through what I got and he suggested that I open a issue with you.

I am getting this error:

[26-Feb-2014 10:23:02 America/Denver] PHP Fatal error: Uncaught exception 'RuntimeException' with message 'Impossible CRON expression' in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:321
Stack trace:
#0 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(157): Cron\CronExpression->getRunDate('2014-02-26 10:2...', 0, false, true)
#1 /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php(252): Cron\CronExpression->getNextRunDate('2014-02-26 10:2...', 0, true)
#2 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(181): Cron\CronExpression->isDue()
#3 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(67): Jobby\BackgroundJob->shouldRun()
#4 /home/brentst1/public_html/sociallev/respond/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php(304): Jobby\BackgroundJob->run()
#5 {main}

thrown in /home/brentst1/public_html/sociallev/respond/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php on line 321

When I feed jobby this:

{"command":"/usr/local/bin/php auto-excel-prep.php 9","schedule":"25 23 * 0 0,1,2,3,4,5,6","output":"log-excel.txt","enabled":"true"} - February 26th, 2014 10:23:01

Any idea why? Cronchecker says that this is valid..

http://cronchecker.net/check?utf8=%E2%9C%93&statement=25+23+*+0+0%2C1%2C2%2C3%2C4%2C5%2C6+ls&commit=Check

(ls just for example.)

Expression with year not working as expected

Test Case:

//valid cron expression
$cronExpression = '* * * * * 2012';
$cron = \Cron\CronExpression::factory($cronExpression);

//last possible run date
$lastRun = \DateTime::createFromFormat('Y-m-d H:i:s', '2012-12-31 23:59:00');

//this throw an RuntimeException: Impossible CRON expression
$nextRun = $cron->getNextRunDate($lastRun);

I think it would be better to return null instead throw an exception

Human readable schedule strings

Great lib! I was surprised that you don't offer a way to parse a cron schedule string into a human readable format. Would this be something you'd be willing to include if a PR was submitted? I think it would make more sense being in your library than in a library on it's own...

Colliding Cron Jobs

Would it be possible to make a function that check colliding schedule?
Ex: */7 * * * * and */3 * * * * would collide at 21 * * * *.

Alternatively, generating cron jobs would make it easier.
Ex: */25 * * * * would generate 25 * * * * and 50 * * * *.
12,40,55 * * * * would generate 12 * * * *, 40 * * * *, 55 * * * *.
(Or maybe more detailed to some extent?)

previous run date bug

hi,
sorry, but i found another huge bug (obviously in php, but anyway it make your library limited usable)
test case:

$cron = Cron\CronExpression::factory('0 0 27 1 0');
$cron->isDue("2011-09-02 12:50:00");
var_dump( $cron->getPreviousRunDate()->format('Y-m-d H:i:s'));

error show
Uncaught exception 'RuntimeException' with message 'Impossible CRON expression'

after debug, i saw freeze in changing date cycle in july.
reason - bug in php DateInterval calculating

$present = new DateTime("2011-07-31 23:59:00");
$past = clone $present;
$past->sub(new DateInterval('P1M'));
var_dump($present,$past,$past->diff($present));

output:

object(DateTime)#1 (3) {
["date"]=> string(19) "2011-07-31 23:59:00"
["timezone_type"]=> int(3)
["timezone"]=> string(3) "UTC"
}
object(DateTime)#2 (3) {
["date"]=> string(19) "2011-07-01 23:59:00"
["timezone_type"]=> int(3)
["timezone"]=> string(3) "UTC"
}
object(DateInterval)#4 (8) {
["y"]=> int(0)
["m"]=> int(0)
["d"]=> int(30)
["h"]=> int(0)
["i"]=> int(0)
["s"]=> int(0)
["invert"]=> int(0)
["days"]=> int(30)
}

as you can see - 31 july - 1 month = july 1 :)
but measure interval between two dates show correct diff - not 1 month, 30 days
here bugreport https://bugs.php.net/bug.php?id=52480

i don know if this bug exist in increment by interval, but that bug should be reflect in docs

or maybe create additional checks and correct this bug (why not?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.