musa
musa

Reputation: 1465

Laravel job pushed to queue event

In Laravel documentation there is Queue::before and Queue::after events. What I'm looking for is "job pushed to queue" or "job created" event, something like Queue::pushed. Is that exists or how can I trigger that event?

In this answer I saw JobPushed event but it's from Laravel Horizon. Is there a way without Horizon?

Queue::before(function (JobProcessing $event) {
    // $event->connectionName
    // $event->job
    // $event->job->payload()
});

Queue::after(function (JobProcessed $event) {
    // $event->connectionName
    // $event->job
    // $event->job->payload()
});

Upvotes: 3

Views: 1731

Answers (1)

reza
reza

Reputation: 1776

you can use your job class cunstructor function as a job created event. a job object constructor is executed when you create a new instance of it. but other functions (for example: handle() and ...) would execute when job is running in queue.

also for something near job pushed to queue you can override the dispatch function of you job class. job objects have an static function dispatch that pushes a new job object into queue.

so your edited job class would be like these:

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SampleJob implements ShouldQueue
{
  use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  /**
   * Create a new job instance.
   *
   * @return void
   */
  public function __construct()
  {
    $this->created();
    // rest of code
  }

  /**
   * Execute the job.
   *
   * @return void
   */
  public function handle()
  {
  }

  public static function dispatch($job)
  {
    SampleJob::dispatch($job);
    $job->pushedToQueue();
  }

  // events 

  public function created()
  {
    // event codes
  }
  public function pushedToQueue()
  {
    // event codes
  }
}

Upvotes: 2

Related Questions