Skip to content

Commit

Permalink
Allow run() to run at arbitrary time
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
merijnvdk committed Sep 13, 2017
1 parent f8374af commit b5ce3aa
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/GO/Scheduler.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,16 @@ public function raw($command, $args = [], $id = null)
/**
* Run the scheduler.
*
* @param DateTime $runTime Optional, run at specific moment
* @return array Executed jobs
*/
public function run()
public function run($runTime = null)
{
$jobs = $this->getQueuedJobs();

$runTime = new DateTime('now');
if (is_null($runTime)) {
$runTime = new DateTime('now');
}

foreach ($jobs as $job) {
if ($job->isDue($runTime)) {
Expand Down
15 changes: 15 additions & 0 deletions tests/GO/SchedulerTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php namespace GO\Job\Tests;

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

Expand Down Expand Up @@ -304,4 +305,18 @@ public function testShouldRunDelayedJobsIfDueWhenCreated()

$this->assertEquals(2, count($executed));
}

public function testShouldRunAtSpecificTime()
{
$scheduler = new Scheduler();
$runTime = new DateTime('2017-09-13 00:00:00');

$scheduler->call(function () {
// do nothing
})->daily('00:00');

$executed = $scheduler->run($runTime);

$this->assertEquals(1, count($executed));
}
}

0 comments on commit b5ce3aa

Please sign in to comment.