M
M
Misty Hedgehog2016-11-30 14:01:11
Message Queues
Misty Hedgehog, 2016-11-30 14:01:11

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();

And there is also an even more wonderful thing, like Queue (and the implementation of the tasks themselves called Job) . So, the question arose - how to ensure that the same Jobone 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());
  }

}

Then I inherit this class, and I use something like this:
// /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();
    }
  }

}

And the question is - how much is this collective farm method? Maybe I missed something in the documentation for Lark?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor, 2016-11-30
@v_decadence

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 question

Ask a Question

731 491 924 answers to any question