Skip to content

Commit

Permalink
Merge pull request #1 from peppeocchi/master
Browse files Browse the repository at this point in the history
update master
  • Loading branch information
Sascha Nos committed Jul 23, 2020
2 parents 9ca45bc + fc19fd9 commit 57be4e0
Show file tree
Hide file tree
Showing 10 changed files with 132 additions and 19 deletions.
3 changes: 0 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
language: php
php:
- '5.6'
- '7.0'
- '7.1'
- '7.2'
- hhvm

matrix:
allow_failures:
- php: 5.6
- php: hhvm
fast_finish: true

Expand Down
59 changes: 54 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ or add the package to your `composer.json`
```json
{
"require": {
"peppeocchi/php-cron-scheduler": "2.*"
"peppeocchi/php-cron-scheduler": "3.*"
}
}
```

Scheduler V3 requires php >= 7.1, please use the [v2 branch](https://github.com/peppeocchi/php-cron-scheduler/tree/v2.x) for php versions < 7.1.

## How it works

Create a `scheduler.php` file in the root your project with the following content.
Expand Down Expand Up @@ -63,7 +65,7 @@ $scheduler->php('path/to/my/script.php');
The `php` method accepts 4 arguments:
- The path to your php script
- The PHP binary to use
- Arguments to be passed to the script
- Arguments to be passed to the script (**NOTE**: You need to have **register_argc_argv** enable in your php.ini for this to work ([ref](https://github.com/peppeocchi/php-cron-scheduler/issues/88)). Don't worry it's enabled by default, so unlessy you've intentionally disabled it or your host has it disabled by default, you can ignore it.)
- Identifier
```php
$scheduler->php(
Expand Down Expand Up @@ -114,7 +116,41 @@ $scheduler->call(
return $args['user'];
},
[
'user' => $user,
['user' => $user],
],
'myCustomIdentifier'
);
```

All of the arguments you pass in the array will be injected to your function.
For example

```php
$scheduler->call(
function ($firstName, $lastName) {
return implode(' ', [$firstName, $lastName]);
},
[
'John',
'last_name' => 'Doe', // The keys are being ignored
],
'myCustomIdentifier'
);
```

If you want to pass a key => value pair, please pass an array within the arguments array

```php
$scheduler->call(
function ($user, $role) {
return implode(' ', [$user['first_name'], $user['last_name']]) . " has role: '{$role}'";
},
[
[
'first_name' => 'John',
'last_name' => 'Doe',
],
'Admin'
],
'myCustomIdentifier'
);
Expand All @@ -125,13 +161,14 @@ $scheduler->call(
There are a few methods to help you set the execution time of your schedules.
If you don't call any of this method, the job will run every minute (* * * * *).

- `at` - This method accepts any expression supported by [mtdowling/cron-expression](https://github.com/mtdowling/cron-expression)
- `at` - This method accepts any expression supported by [dragonmantank/cron-expression](https://github.com/dragonmantank/cron-expression)
```php
$scheduler->php('script.php')->at('* * * * *');
```
- `everyMinute` - Run every minute
- `everyMinute` - Run every minute. You can optionally pass a `$minute` to specify the job runs every `$minute` minutes.
```php
$scheduler->php('script.php')->everyMinute();
$scheduler->php('script.php')->everyMinute(5);
```
- `hourly` - Run once per hour. You can optionally pass the `$minute` you want to run, by default it will run every hour at minute '00'.
```php
Expand Down Expand Up @@ -405,6 +442,18 @@ The resons for this feature are described [here](https://github.com/peppeocchi/p
$fakeRunTime = new DateTime('2017-09-13 00:00:00');
$scheduler->run($fakeRunTime);
```
### Job failures
If some job fails, you can access list of failed jobs and reasons for failures.

```php
// get all failed jobs and select first
$failedJob = $scheduler->getFailedJobs()[0];

// exception that occurred during job
$exception = $failedJob->getException();

// job that failed
$job = $failedJob->getJob();
```
## License
[The MIT License (MIT)](LICENSE)
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
],
"minimum-stability": "dev",
"require": {
"php": ">=5.5.9",
"mtdowling/cron-expression": "~1.0"
"php": "^7.1",
"dragonmantank/cron-expression": "^2.3"
},
"require-dev": {
"phpunit/phpunit": "~5.7",
Expand Down
32 changes: 32 additions & 0 deletions src/GO/FailedJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php namespace GO;

use Exception;

class FailedJob
{
/**
* @var Job
*/
private $job;

/**
* @var Exception
*/
private $exception;

public function __construct(Job $job, Exception $exception)
{
$this->job = $job;
$this->exception = $exception;
}

public function getJob(): Job
{
return $this->job;
}

public function getException(): Exception
{
return $this->exception;
}
}
2 changes: 2 additions & 0 deletions src/GO/Job.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ public function __construct($command, $args = [], $id = null)
} else {
if (is_string($command)) {
$this->id = md5($command);
} elseif (is_array($command)) {
$this->id = md5(serialize($command));
} else {
/* @var object $command */
$this->id = spl_object_hash($command);
Expand Down
6 changes: 3 additions & 3 deletions src/GO/Scheduler.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class Scheduler
/**
* Failed jobs.
*
* @var array
* @var FailedJob[]
*/
private $failedJobs = [];

Expand Down Expand Up @@ -256,7 +256,7 @@ public function getExecutedJobs()
*/
private function pushFailedJob(Job $job, Exception $e)
{
$this->failedJobs[] = $job;
$this->failedJobs[] = new FailedJob($job, $e);

$compiled = $job->compile();

Expand All @@ -273,7 +273,7 @@ private function pushFailedJob(Job $job, Exception $e)
/**
* Get the failed jobs.
*
* @return array
* @return FailedJob[]
*/
public function getFailedJobs()
{
Expand Down
14 changes: 11 additions & 3 deletions src/GO/Traits/Interval.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,19 @@ public function date($date)
/**
* Set the execution time to every minute.
*
* @param int|string|null When set, specifies that the job will be run every $minute minutes
*
* @return self
*/
public function everyMinute()
public function everyMinute($minute = null)
{
return $this->at('* * * * *');
$minuteExpression = '*';
if ($minute !== null) {
$c = $this->validateCronSequence($minute);
$minuteExpression = '*/' . $c['minute'];
}

return $this->at($minuteExpression . ' * * * *');
}

/**
Expand Down Expand Up @@ -405,6 +413,6 @@ private function validateCronRange($value, $min, $max)
);
}

return $value;
return (int) $value;
}
}
10 changes: 10 additions & 0 deletions tests/GO/IntervalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,4 +264,14 @@ public function testShouldFailIfDifferentYear()
// As instance of datetime
$this->assertFalse($job->date('2018-01-01')->isDue(new \DateTime('2019-01-01')));
}

public function testEveryMinuteWithParameter()
{
$job = new Job('ls');

// Job should run at 10:00, 10:05, 10:10 etc., but not at 10:02
$this->assertTrue($job->everyMinute(5)->isDue(\DateTime::createFromFormat('H:i', '10:00')));
$this->assertFalse($job->everyMinute(5)->isDue(\DateTime::createFromFormat('H:i', '10:02')));
$this->assertTrue($job->everyMinute(5)->isDue(\DateTime::createFromFormat('H:i', '10:05')));
}
}
9 changes: 9 additions & 0 deletions tests/GO/JobTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public function testShouldAlwaysGenerateAnId()
return true;
});
$this->assertTrue(is_string($job2->getId()));

$job3 = new Job(['MyClass', 'myMethod']);
$this->assertTrue(is_string($job3->getId()));
}

public function testShouldGenerateIdFromSignature()
Expand All @@ -23,6 +26,9 @@ public function testShouldGenerateIdFromSignature()

$job2 = new Job('whoami');
$this->assertNotEquals($job1->getId(), $job2->getId());

$job3 = new Job(['MyClass', 'myMethod']);
$this->assertNotEquals($job1->getId(), $job3->getId());
}

public function testShouldAllowCustomId()
Expand All @@ -31,6 +37,9 @@ public function testShouldAllowCustomId()

$this->assertNotEquals(md5('ls'), $job->getId());
$this->assertEquals('aCustomId', $job->getId());

$job2 = new Job(['MyClass', 'myMethod'], null, 'myCustomId');
$this->assertEquals('myCustomId', $job2->getId());
}

public function testShouldKnowIfDue()
Expand Down
12 changes: 9 additions & 3 deletions tests/GO/SchedulerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use GO\Job;
use DateTime;
use GO\FailedJob;
use GO\Scheduler;
use PHPUnit\Framework\TestCase;

Expand Down Expand Up @@ -82,7 +83,7 @@ public function testShouldMarkJobAsFailedIfScriptPathIsInvalid()
$scheduler->run();
$fail = $scheduler->getFailedJobs();
$this->assertCount(1, $fail);
$this->assertContainsOnlyInstancesOf(Job::class, $fail);
$this->assertContainsOnlyInstancesOf(FailedJob::class, $fail);
}

public function testShouldQueueAShellCommand()
Expand Down Expand Up @@ -152,8 +153,9 @@ public function testShouldKeepTrackOfFailedJobs()
{
$scheduler = new Scheduler();

$scheduler->call(function () {
throw new \Exception('Something failed');
$exception = new \Exception('Something failed');
$scheduler->call(function () use ($exception) {
throw $exception;
});

$this->assertEquals(count($scheduler->getFailedJobs()), 0);
Expand All @@ -162,6 +164,10 @@ public function testShouldKeepTrackOfFailedJobs()

$this->assertEquals(count($scheduler->getExecutedJobs()), 0);
$this->assertEquals(count($scheduler->getFailedJobs()), 1);
$failedJob = $scheduler->getFailedJobs()[0];
$this->assertInstanceOf(FailedJob::class, $failedJob);
$this->assertSame($exception, $failedJob->getException());
$this->assertInstanceOf(Job::class, $failedJob->getJob());
}

public function testShouldKeepExecutingJobsIfOneFails()
Expand Down

0 comments on commit 57be4e0

Please sign in to comment.