Laravel comes with this functionality out-of-the-box...
Set limit for queued jobs
I need to implement processing of big (different) amount of products - take them from one api and then send it to another api. Problem is that api where i should send this products has an limit (also different) - 2/4/etc requests per second.
I test how can i do it with this way:
call jobs like this:
collect(range(1, 100))->each(function ($i) {
TestJob::dispatch($i);
});
for my job i downloaded spatie/laravel-rate-limited-job-middleware package from composer
and here is my job class:
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, Batchable;
protected $i;
public function __construct($i)
{
$this->i = $i;
}
public function handle()
{
Log::alert($this->i);
}
public function middleware()
{
$rateLimitedMiddleware = (new RateLimited(false))
->allow(2)
->everySeconds(1)
->releaseAfterSeconds(2);
return [$rateLimitedMiddleware];
}
}
and here what i got in my log file:
[2024-04-17 12:43:12] local.ALERT: 1
[2024-04-17 12:43:12] local.ALERT: 2
[2024-04-17 12:43:16] local.ERROR: App\Jobs\TestJob has been attempted too many times or run too long. The job may have previously timed out. {"exception":"[object] (Illuminate\Queue\MaxAttemptsExceededException(code: 0): App\Jobs\TestJob has been attempted too many times or run too long. The job may have previously timed out. at /home/illichov11/projects/pims-dev.local/vendor/laravel/framework/src/Illuminate/Queue/Worker.php:746)
[stacktrace]
(this error with trace reapeted for 98 times - for all anothers jobs)
But i need to something like pause processing another jobs, so that only 2 jobs will processed in 1 second, then - another 2 etc...
I am using database queue connection (my db is mariadb)
Please or to participate in this conversation.