laravelqueue

In Laravel, how to control whether a Job should be processed via queue or synchronously


I wrote Jobs for most of my "business transactions" which turns out to work quiet well in terms of clean, readable architecture.

In the Job itself, I've to decide whether the Job, once dispatched in my code, should run synchronously or via a queue.

Most of the time I can clearly decide what fits best for a job. Nevertheless, I have situations, where it's important to know, that the task has been fulfilled, before I can continue further processes. Sometimes, it's okay to queue the task because there are no dependencies.

In this situations I'd love being able to control this flow in my code.

For example by doing

$this->dispatch(new MyJob());

to use the default way and

$this->queue(new MyJob()) or $this->run(new MyJob()) to force either way.

Is that somehow possible, or am I totally confused about this topic?


Solution

  • In Laravel 5.2 at least I think you are able to do this by using either dispatch or dispatchNow.

    The DispatchesJobs trait offers both of these methods, which in turn defer to the Illuminate\Bus\Dispatcher implementation.

    You should create a job that is queueable, in that it implements the ShouldQueue interface:

    class MyJob extends Job implements ShouldQueue
    {
        // ...
    }
    

    Now, when it comes to dispatching your job to the queue, you can run:

    $this->dispatch(new MyJob());
    

    Or if you would rather dispatch the job immediately, and not have it queued you can run:

    $this->dispatchNow(new MyJob());
    

    Alternatively, you could always create both queueable and non-queueable versions of your job if you wanted to go down that route. You can easily do that without repeating yourself by extending the non-queueable job and implementing the ShouldQueue interface.

    class MyJob extends Job
    {
        public function handle()
        {
            // Write your implementation
        }
    } 
    

    and

    class MyQueueableJob extends MyJob implements ShouldQueue
    {
        // No need to write an implementation since it extends MyJob
    }