Answer the question
In order to leave comments, you need to log in
WithoutOverlapping for Queue in Larvel 5?
Hello %username%.
In L5 (as in previous versions) there is a wonderful schedule -er that allows you to run tasks (formulated as commands for artisan) on a schedule, and at the task initialization step we can use a wonderful "flag" ->withoutOverlapping()
that prevents the command from running if it is not yet incomplete, for example:
$schedule
->command('queue:listen')
->everyMinute()
->withoutOverlapping();
Job
) . So, the question arose - how to ensure that the same Job
one will not be launched twice in one unit of time? Since the operation runs long in it, there is a chance that it will be executed twice. The context of its call is not important yet. I did like this:// /app/Jobs/Job.php
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class Job implements ShouldQueue {
use InteractsWithQueue,
Queueable,
SerializesModels;
/**
* Get path to the 'lock' file.
*
* @return string
*/
protected function getLockFilePath() {
return storage_path('framework/schedule-' . md5(__NAMESPACE__ . get_class($this)) . '.lock');
}
/**
* Lock current job (PREVENTING OVERLAPPING).
*
* @return boolean
*/
protected function lock() {
return touch($this->getLockFilePath());
}
/**
* Disable locking.
*
* @return boolean
*/
protected function unlock() {
return unlink($this->getLockFilePath());
}
/**
* Check - job is locked?
*
* @return boolean
*/
protected function locked() {
return file_exists($this->getLockFilePath());
}
}
// /app/Jobs/SomeJob.php
<?php
namespace App\Jobs;
use App\Jobs\Job;
class SomeJob extends Job {
/**
* Execute the job.
*
* @return void
*/
public function handle() {
// PREVENTING OVERLAPPING
if (!$this->locked()) {
$this->lock();
// LONG-LONG operation is here
$this->unlock();
}
}
}
Answer the question
In order to leave comments, you need to log in
As far as I understand, during the work
Laravel looks at the work table and starts the raw ones one by one.
Therefore, if a Job is added once, it will not be executed more than once if there are no errors during processing. So any improvements here are unnecessary.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question