I am trying to run a time consuming script in the background with Laravel 8, but cant quite get it to work. I try to follow the docs from here https://laravel.com/docs/8.x/queues in combination with the tutorial found here: https://learn2torials.com/a/how-to-create-background-job-in-laravel
As per docs, I should run the following commands to get strateted with Queue/jobs in Laravel
php artisan queue:table
php artisan migrate
Then we should create our Job with the following command
php artisan make:job TestJob
In App\Jobs\
is our newly created job-file: TestJob.php
Again following the docs, I should put my time consuming script/code in the handle()
method of TestJob.php
. I have written the following code in handle()
for test purposes:
public function handle()
{
//Do some time-consuming stuff
sleep(30);
}
Next, according to the docs, we should dispatch our job with the following line of code TestJob::dispatch()
, anywhere in our app, so for test purposes, I put this line directly into our routes file, like this:
Route::get('/', function () {
//Run this job in the background and continue
\App\Jobs\TestJob::dispatch();
//After job is started/Queued return view
return view('welcome');
});
That should be it, as I understand from the docs, but it is not working as I expected. The code in handle()
gets executed, but the return view('welcome');
is executed AFTER the the job is completed.
I was expecting the script to be executed and while running in the background the next line of code will be executed. How can I make it run in the background so the user do not have to wait for the script to finish?
I have googled a lot and according to the tutorial linked to earlier, I should have the following line: QUEUE_DRIVER=database
in my .env file. I have sat this, and also sat it in Config\queue.php with the following line: 'default' => env('QUEUE_CONNECTION', 'database'),
, but still same result
I also found the following solution for Laravel 5 here on SO (link), where there is suggested that we also should run the following code to get it to work: php artisan queue:listen
, but its the same result again
Any help would be much appreciated!