calling job method from Queue::before Laravel

44 Views Asked by At

ShouldBeUnique only available on Laravel 8 and newer. But I'm still using Laravel 6. So I'm trying to implement the same functionality;

<?php

namespace App\Jobs;

use Illuminate\Support\Facades\Cache;

abstract class UniqueJob extends Job {

    private $ttl = 60 * 60 * 24; // 24 hours in seconds

    abstract public function uniqueId(): string;

    public function acquireLock()
    {
        return Cache::lock($this->uniqueId(), $this->ttl)->get();
    }

    public function releaseLock()
    {
        return Cache::lock($this->uniqueId())->forceRelease();
    }

    public function failed()
    {
        $this->releaseLock();
    }
}

<?php

use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use App\Jobs\UniqueJob;

class AppServiceProvider extends ServiceProvider
{
   public function boot()
   {
       ...
       Queue::before(function (JobProcessing $event) {

            if (is_subclass_of($event->job->payload()['displayName'], UniqueJob::class)) 
            {
                if (!$event->job->acquireLock()) {
                    $event->job->delete();
                }
            }
        });
 
        Queue::after(function (JobProcessed $event) {

            if (is_subclass_of($event->job->payload()['displayName'], UniqueJob::class)) 
            {
                $event->job->releaseLock();
            }
        });
       ...
   }
   ...
}

but I'm getting Call to undefined method Illuminate\Queue\Jobs\SyncJob::acquireLock() error. Am I missing something, or is there any other way?

0

There are 0 best solutions below