我有一个函数需要花很长时间才能执行,所以我想在后台运行此函数吗?
我想在用户单击按钮时运行此功能。 并且不想从终端运行任何命令。
谢谢
答案 0 :(得分:0)
要实施队列系统,必须遵循以下步骤。
-在按钮上单击路由(/ usertask / performAction) 在您的控制器中假设(UserTaskController.php) 1-为您的工作添加名称空间。
<?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
}
现在创建一个作业文件。 (ProcessTask.php)在作业文件夹中。 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');
}
}
?>
////现在您可以在终端()中运行作业了
php arrtisan queue:listen --queue=ProcessTask --timeout=600
在您的终端中(或您可以将其放置在主管中)
与队列驱动程序有关的设置-
/var/www/html/infinito/config/queue.php
make QUEUE_DRIVER as database.
'default' => env('QUEUE_DRIVER', 'database'),