Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Illuminate/Foundation/Bus/PendingDispatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Illuminate\Foundation\Bus;

use Closure;
use Illuminate\Bus\UniqueLock;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Container\Container;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Contracts\Cache\Repository as Cache;
Expand Down Expand Up @@ -129,6 +131,24 @@ public function withoutDelay()
return $this;
}

/**
* Spread the job out by delaying dispatches respecting the rate limit.
*
* @param \Illuminate\Cache\RateLimiting\Limit|(\Closure(mixed $job): \Illuminate\Cache\RateLimiting\Limit) $limit
* @param int $index
* @return $this
*/
public function spreadWithDelay($limit, $index)
{
if ($limit instanceof Closure) {
$limit = $limit($this->job);
}

$delay = (int) (($index / $limit->maxAttempts) * $limit->decaySeconds);

return $this->delay($delay);
}

/**
* Indicate that the job should be dispatched after all database transactions have committed.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Bus/BusPendingDispatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

namespace Illuminate\Tests\Bus;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Fluent;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
Expand Down Expand Up @@ -76,6 +79,24 @@ public function testWithoutDelay()
$this->pendingDispatch->withoutDelay();
}

public function testSpreadWithDelay()
{
$job = new Fluent;
$pendingDispatch = new PendingDispatchWithoutDestructor($job);
$limit = Limit::perSecond(1, 15);

$pendingDispatch->spreadWithDelay($limit, 0);
$this->assertSame(0, $job->delay);
$pendingDispatch->spreadWithDelay($limit, 1);
$this->assertSame(15, $job->delay);
$pendingDispatch->spreadWithDelay($limit, 2);
$this->assertSame(30, $job->delay);
$pendingDispatch->spreadWithDelay($limit, 3);
$this->assertSame(45, $job->delay);
$pendingDispatch->spreadWithDelay($limit, 4);
$this->assertSame(60, $job->delay);
}

public function testAfterCommit()
{
$this->job->shouldReceive('afterCommit')->once();
Expand Down
Loading