Skip to content

Instantly share code, notes, and snippets.

@thedom85
Last active July 15, 2022 13:53
Show Gist options
  • Save thedom85/80df1f3acf134e9e2cce3b2e13d62b14 to your computer and use it in GitHub Desktop.
Save thedom85/80df1f3acf134e9e2cce3b2e13d62b14 to your computer and use it in GitHub Desktop.

Php Laravel Queues

Step1 - Crete migration

php artisan queue:table

Step2 - Run Migration

php artisan migrate

Step3 - Config env file

QUEUE_CONNECTION=database

Step4 - Create Job

  php artisan make:job CalculateDataJob
<?php

namespace App\Jobs;

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

class CalculateDataJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        for ($x = 1; $x <= 10; $x++) {
           sleep(2);
        }
        return 0;
    }
}

Step5 - Create Command DemoCron

  php artisan make:command DemoCron
  <?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
use App\Jobs\CalculateDataJob;

class DemoCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Example cron ';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        CalculateDataJob::dispatch();
        return 0;
    }
}

Step5 - Run Queues and Command

 php artisan queue:work
  php artisan demo:cron
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment