Skip to content

Commit 83391f5

Browse files
authored
New features for custom job/scheduler running times (#29)
* Clean up * Updated phpunit * Refactoring for v2 * Refectory for v2 pt2 * Required dev php7 Phpunit v6 requires php7 to run * Fancy helpers * Prioritise jobs in background * Use temp arrays to prioritise jobs * Coveralls * Coverall config * Adjusted waiting time on test * Typo fix * Removed deprecated flag * Added Coverage badge to readme * Removed psr/log suggestion * Fixed typo in composer.json * Fixes from styleci * Downgraded phpunit Using an older version of phpunit to allow testing on php5, as phpunit v6 requires php7 * Added php 7.1 supported version * More fixes from styleci * Fixes from styleci * Reordered badges + styleci badge * Increased tests waiting time when testing file output * Typo in the documentation Ref #16 * Fix #20 Added support for SwiftMailer ^6.0 ::newInstance() method has been deprecated, along with Swift_MailTransport. The default mail transport is now sendmail when using swiftmailer https://legalhackers.com/advisories/SwiftMailer-Exploit-Remote-Code-Exec -CVE-2016-10074-Vuln.html * Implementation of #23 using `then` method Similar implementation of the PR #23 submitted by @Badyto Reused the same tests on that PR There is also a possible breaking change with the output passed to the callback in the `then` method, when executing a script the output will be now an array instead of a string. * Added scheduler test This test ensures that if a job is delayed by e.g. a previous job, it will run if it was due when the scheduler ran. * Removed comment from test * Allow run() to be executed multiple times (#24) * Allow run() to be executed multiple times The current code expects the run() to be called only once. This is fine if you start the scheduler from cron each minute and re-initialize it each time. If you want to manually run the scheduler, or maybe have a lot of jobs you do not want to init each minute, it would be useful to call run() multiple times in the lifetime of the scheduler. In this case the collected data of the last run should be reset. the executedJobs, failedJobs and outputSchedule. * Allow queued jobs to be removed If the scheduler is used to do multiple runs then it would be useful to reset all queued Jobs. Currently the only way to do this is by re-creating the scheduler object. But if the object is injected in the code then this is not practical.. * Fix StyleCI analysis failure Comment format fixed. * Allow run() to be executed multiple times After discussion with @peppeocchi make the re-running manually triggered. So added a resetRun() method which can be called before each run(). Also adjusted the test for this. * Allow run() to be executed multiple times The isDue check on the jobs is not provided a datetime in the run() method. This means they use the creation time of the job as the 'current' time to compare against. Most likely this creation time is approx the time run() is called so normally this is no problem. But if setting up the job schedule takes more time then I would say, using the creation time as run time is unexpected. And if you run run() multiple times then it will always run the same jobs because the time never changes. So now provide an explicit run time for all jobs, which is the same for all jobs each run. * Fix StyleCI analysis failure Remove empty line * Allow run() to run at arbitrary time (#28) Currently when run() is called it uses the current time as the run timestamp. However it would be useful to run the scheduler at a specific time. So allow an optional param with a DateTime to run(). Reasons for running at a specific time other than now() could be: - Catching up on 'missed' runs, eg. when the system was down. - Making sure the scheduler runs at an intended timestamp eg. when cron is started at midnight it could be slow and start the php process only at 00:01 and thus missing all midnight schedules. - Improve testability of the scheduler (fake the time) * Minor change + documentation new features
1 parent a6e4430 commit 83391f5

File tree

6 files changed

+163
-8
lines changed

6 files changed

+163
-8
lines changed

README.md

+30
Original file line numberDiff line numberDiff line change
@@ -295,3 +295,33 @@ $scheduler->php('script.php')->then(function ($output) {
295295
log('Job executed!');
296296
}, true);
297297
```
298+
299+
### Multiple scheduler runs
300+
In some cases you might need to run the scheduler multiple times in the same script.
301+
Although this is not a common case, the following methods will allow you to re-use the same instance of the scheduler.
302+
```php
303+
# some code
304+
$scheduler->run();
305+
# ...
306+
307+
// Reset the scheduler after a previous run
308+
$scheduler->resetRun()
309+
->run(); // now we can run it again
310+
```
311+
312+
Another handy method if you are re-using the same instance of the scheduler with different jobs (e.g. job coming from an external source - db, file ...) on every run, is to clear the current scheduled jobs.
313+
```php
314+
$scheduler->clearJobs()
315+
->resetRun()
316+
->run(); // now we can run it again
317+
```
318+
319+
### Faking scheduler run time
320+
When running the scheduler you might pass an `DateTime` to fake the scheduler run time.
321+
The resons for this feature are described [here](https://github.com/peppeocchi/php-cron-scheduler/pull/28);
322+
323+
```
324+
// ...
325+
$fakeRunTime = new DateTime('2017-09-13 00:00:00');
326+
$scheduler->run($fakeRunTime);
327+
```

src/GO/Job.php

+9-2
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,13 @@ class Job
8181
*/
8282
private $output;
8383

84+
/**
85+
* The return code of the executed job.
86+
*
87+
* @var int
88+
*/
89+
private $returnCode = 0;
90+
8491
/**
8592
* Files to write the output of the job.
8693
*
@@ -361,7 +368,7 @@ public function run()
361368
if (is_callable($compiled)) {
362369
$this->output = $this->exec($compiled);
363370
} else {
364-
$this->output = exec($compiled);
371+
exec($compiled, $this->output, $this->returnCode);
365372
}
366373

367374
$this->finalise();
@@ -492,7 +499,7 @@ private function finalise()
492499

493500
// Call any callback defined
494501
if (is_callable($this->after)) {
495-
call_user_func($this->after, $this->output);
502+
call_user_func($this->after, $this->output, $this->returnCode);
496503
}
497504
}
498505

src/GO/Scheduler.php

+32-2
Original file line numberDiff line numberDiff line change
@@ -149,14 +149,19 @@ public function raw($command, $args = [], $id = null)
149149
/**
150150
* Run the scheduler.
151151
*
152+
* @param DateTime $runTime Optional, run at specific moment
152153
* @return array Executed jobs
153154
*/
154-
public function run()
155+
public function run(Datetime $runTime = null)
155156
{
156157
$jobs = $this->getQueuedJobs();
157158

159+
if (is_null($runTime)) {
160+
$runTime = new DateTime('now');
161+
}
162+
158163
foreach ($jobs as $job) {
159-
if ($job->isDue()) {
164+
if ($job->isDue($runTime)) {
160165
try {
161166
$job->run();
162167
$this->pushExecutedJob($job);
@@ -169,6 +174,21 @@ public function run()
169174
return $this->getExecutedJobs();
170175
}
171176

177+
/**
178+
* Reset all collected data of last run.
179+
*
180+
* Call before run() if you call run() multiple times.
181+
*/
182+
public function resetRun()
183+
{
184+
// Reset collected data of last run
185+
$this->executedJobs = [];
186+
$this->failedJobs = [];
187+
$this->outputSchedule = [];
188+
189+
return $this;
190+
}
191+
172192
/**
173193
* Add an entry to the scheduler verbose output array.
174194
*
@@ -268,4 +288,14 @@ public function getVerboseOutput($type = 'text')
268288
throw new InvalidArgumentException('Invalid output type');
269289
}
270290
}
291+
292+
/**
293+
* Remove all queued Jobs.
294+
*/
295+
public function clearJobs()
296+
{
297+
$this->jobs = [];
298+
299+
return $this;
300+
}
271301
}

tests/GO/JobTest.php

+21-4
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,6 @@ public function testShouldGenerateIdFromSignature()
2525
$this->assertNotEquals($job1->getId(), $job2->getId());
2626
}
2727

28-
// Test scheduler: test that you schedule a job at one time, then wait 1 minute
29-
// and check that the Job still needs to be executed
30-
3128
public function testShouldAllowCustomId()
3229
{
3330
$job = new Job('ls', [], 'aCustomId');
@@ -353,7 +350,7 @@ public function testShouldReturnOutputOfJobExecution()
353350
$command = PHP_BINARY . ' ' . __DIR__ . '/../test_job.php';
354351
$job3 = new Job($command);
355352
$job3->inForeground()->run();
356-
$this->assertEquals('hi', $job3->getOutput());
353+
$this->assertEquals(['hi'], $job3->getOutput());
357354
}
358355

359356
public function testShouldRunCallbackAfterJobExecution()
@@ -392,6 +389,26 @@ public function testShouldRunCallbackAfterJobExecution()
392389
$job2Result === $job2->getOutput());
393390
}
394391

392+
public function testThenMethodShouldPassReturnCode()
393+
{
394+
$command_success = PHP_BINARY . ' ' . __DIR__ . '/../test_job.php';
395+
$command_fail = $command_success . ' fail';
396+
397+
$run = function ($command) {
398+
$job = new Job($command);
399+
$testReturnCode = null;
400+
401+
$job->then(function ($output, $returnCode) use (&$testReturnCode, &$testOutput) {
402+
$testReturnCode = $returnCode;
403+
})->run();
404+
405+
return $testReturnCode;
406+
};
407+
408+
$this->assertEquals(0, $run($command_success));
409+
$this->assertNotEquals(0, $run($command_fail));
410+
}
411+
395412
public function testThenMethodShouldBeChainable()
396413
{
397414
$job = new Job('ls');

tests/GO/SchedulerTest.php

+67
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php namespace GO\Job\Tests;
22

3+
use DateTime;
34
use GO\Scheduler;
45
use PHPUnit\Framework\TestCase;
56

@@ -252,4 +253,70 @@ public function testShouldPrioritizeJobsInBackround()
252253
$this->assertEquals('async_background', $jobs[0]->getId());
253254
$this->assertEquals('async_foreground', $jobs[1]->getId());
254255
}
256+
257+
public function testCouldRunTwice()
258+
{
259+
$scheduler = new Scheduler();
260+
261+
$scheduler->call(function () {
262+
return true;
263+
});
264+
265+
$scheduler->run();
266+
267+
$this->assertCount(1, $scheduler->getExecutedJobs(), 'Number of executed jobs');
268+
269+
$scheduler->resetRun();
270+
$scheduler->run();
271+
272+
$this->assertCount(1, $scheduler->getExecutedJobs(), 'Number of executed jobs');
273+
}
274+
275+
public function testClearJobs()
276+
{
277+
$scheduler = new Scheduler();
278+
279+
$scheduler->call(function () {
280+
return true;
281+
});
282+
283+
$this->assertCount(1, $scheduler->getQueuedJobs(), 'Number of queued jobs');
284+
285+
$scheduler->clearJobs();
286+
287+
$this->assertCount(0, $scheduler->getQueuedJobs(), 'Number of queued jobs');
288+
}
289+
290+
public function testShouldRunDelayedJobsIfDueWhenCreated()
291+
{
292+
$scheduler = new Scheduler();
293+
$currentTime = date('H:i');
294+
295+
$scheduler->call(function () {
296+
$s = (int) date('s');
297+
sleep(60 - $s + 1);
298+
})->daily($currentTime);
299+
300+
$scheduler->call(function () {
301+
// do nothing
302+
})->daily($currentTime);
303+
304+
$executed = $scheduler->run();
305+
306+
$this->assertEquals(2, count($executed));
307+
}
308+
309+
public function testShouldRunAtSpecificTime()
310+
{
311+
$scheduler = new Scheduler();
312+
$runTime = new DateTime('2017-09-13 00:00:00');
313+
314+
$scheduler->call(function () {
315+
// do nothing
316+
})->daily('00:00');
317+
318+
$executed = $scheduler->run($runTime);
319+
320+
$this->assertEquals(1, count($executed));
321+
}
255322
}

tests/test_job.php

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
11
<?php
22

33
echo 'hi';
4+
5+
if (in_array('fail', $argv)) {
6+
exit(1);
7+
}

0 commit comments

Comments
 (0)