Reputation: 2111
I have one function which take long time to execute so i want to run this function in background can it's possible?
I want to run this function on user click on button. and don't want to run any command from terminal.
Thanks
Upvotes: 0
Views: 1384
Reputation: 1561
For implementing queue system these steps needs to be followed.
-- on button click route (/usertask/performAction) In your controller suppose (UserTaskController.php) 1- add namespace for your jobs.
<?php
use App\Jobs\ProcessTask; // job class that will be created later
class UserTaskController extends Controller
{
// controllers function
function performAction()
{
...
...
...
// code to place background task
$data = [];
$job = ( new ProcessTask($userId, $data))->onQueue('ProcessTask');
if ($this->dispatch($job)) {
info('job dispatched');
} else {
info('job dispatch failed');
}
// code to place background task ends
}
now create a job file. (ProcessTask.php) inside your jobs folder. ProcessTask.php
--------
<?php
namespace App\Jobs;
use Log;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class ProcessTask extends Job implements ShouldQueue
{
use InteractsWithQueue,
SerializesModels;
/**
* Create a new command instance.
*
* @return void
*/
protected $userId;
protected $data;
public function __construct($userId, $data)
{
$this->userId = $userId;
$this->data = $data;
}
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
try {
// perform your task
/*
$this->userId
$this->data
*/
return true;
} catch (\Exception $e) {
Log::error('ProcessTask:: Exception occured ');
Log::error($e);
$this->release(); //release the job back to queue, as attempts increase fail to be
return false;
}
}
public function failed()
{
Log::info('ProcessTask :: failed ends');
}
}
?>
/// now you can run your jobs in terminal ()
php arrtisan queue:listen --queue=ProcessTask --timeout=600
in your terminal(or you can place this in supervisor)
settings related to queue driver--
/var/www/html/infinito/config/queue.php
make QUEUE_DRIVER as database.
'default' => env('QUEUE_DRIVER', 'database'),
Upvotes: 1