Showing posts with label Job Scheduler. Show all posts
Showing posts with label Job Scheduler. Show all posts

Saturday, July 29, 2017

Laravel 5 | How to create Queue and Run Jobs using worker in Laravel | How to execute a job immediately using Laravel Queue | Job Listener Laravel | Schedule And Execute Job Laravel

At first need to create an Job class inside "project/app/jobs" directory. Laravel 5 | How to create Queue and Run Jobs using worker in Laravel | How to execute a job immediately using Laravel Queue | Job Listener Laravel | Schedule And Execute Job Laravel.

Sample job class:


<?php
namespace App\Jobs;

use Log;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class MyTestJob implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels, Queueable;

    private $param1;
    private $param2;

    public function __construct($param1, $param2)
    {
        $this->param1 = $param1;
        $this->param2 = $param2;
    }

    public function handle(Mailer $mailer)
    {
        /* After 3 Times Failed, Job Will Be Released From Queue */
        if ($this->attempts() > 3) {
            Log::info("Max try failed");
            return;
        }
        $to_email = "pritomkucse@gmail.com";
        $mailer->send('emails.some_file_name',
            [
                'param1' => "Param1 value",
                'param2' => "Param2 value"
            ],
            function ($message) use ($to_email) {
                $message->from('from@address.domain', 'From Text');
                $message->subject("Test Subject");
                $message->to($to_email);
            });
    }
}

Below line is to schedule job with 30 seconds delay:

app("Illuminate\\Contracts\\Bus\\Dispatcher")->dispatch((new MyTestJob("1", "2"))->delay(30)); 

And this is time to start queue for job listen. Open command prompt and navigate to "laravel_project"/"project" and execute following command:

php artisan queue:listen --timeout=120

And every time a new job scheduled, this command will execute them on time.