Skip to content

Instantly share code, notes, and snippets.

@lukecurtis93
Last active February 7, 2019 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukecurtis93/06ee64134295a6878b14eecd6c4622db to your computer and use it in GitHub Desktop.
Save lukecurtis93/06ee64134295a6878b14eecd6c4622db to your computer and use it in GitHub Desktop.
A Laravel Throttle Job Example
<?php
namespace App\Http\Controllers;
use App\Jobs\TestJob;
use Illuminate\Http\Request;
class TestController extends Controller
{
//
public function index()
{
for($i = 0; $i < 50; $i++){
dispatch(new TestJob($i));
}
}
}
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Creativecurtis\Laramyob\Laramyob;
use Illuminate\Support\Facades\Redis;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $num;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($num)
{
//
$this->num = $num;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
Redis::throttle('myob')->allow(2)->every(1)->then(function () {
\Log::info('Processed: '.$this->num);
}, function () {
// Could not obtain lock...
// This doesn't mean its failed and wont retry!
// It just means it couldn't lock into the thread, so will release its position and try again later
\Log::info('did not process: '.$this->num);
return $this->release(1);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment