简体   繁体   中英

Laravel 5.8 - execute background job from console command

My project is based on Laravel 5.8.
I have a console command which perform some heavy tasks (generating very big PDF files, sending massive emails, etc.)

I tried to move these tasks to a background processes using jobs .
Here is what I did in order to test how it works:

php artisan make:job TestJob

The job file:

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

    private $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        sleep(5);
        $date = new \DateTime();
        $currentDateTime = $date->format('Ymd-His');
        $logFileName = "logs/testjob-$currentDateTime.log";
        $content = var_export($this->data, true);
        $res = Storage::disk('local')->put($logFileName, $content);
        echo "[TestJob] Print to log file: $logFileName\n";
    }
}

Console command file:

public function handle()
{
    echo "[Console Command] Starting...\n";

    $someData = [
        'First name' => 'John',
        'Surname' => 'Doe'
    ];
    TestJob::dispatch($someData);
    echo "[Console Command] Finished!\n";
}

On execution, this is the output:

[Console Command] Starting...
                                                                <<< delay 5 sec.   
[TestJob] Print to log file: logs/testjob-20210628-114321.log
[Console Command] Finished!

The problem:
The job is executed inside the script, and not in background .

What should I do to make it run in background?

You should change your queue connection (driver) from sync to redis (or another supported queue driver). You can do it in your .env file (for example: QUEUE_CONNECTION=database).

https://laravel.com/docs/5.8/queues#driver-prerequisites

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM