【发布时间】:2019-11-23 11:08:45
【问题描述】:
我是 Laravel 的新手,并尝试创建我的第一个后台任务。
使用的文档:https://laravel.com/docs/master/queues
工作:(ProcessDatabaseImport.php)
<?php
namespace App\Jobs;
use App\Contact;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;
class ProcessDatabaseImport implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $file;
/**
* Create a new job instance.
*
* @param String $filePath
* @return void
*/
public function __construct($filePath)
{
// init File object "database/data/contacts.json"
$this->file = base_path($filePath);
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Log::info('Hello world! file: '.$this->file);
}
/**
* Determine the time at which the job should timeout.
*
* @return \DateTime
*/
public function retryUntil()
{
return now()->addSeconds(30);
}
}
?>
JobController.php:
<?php
namespace App\Http\Controllers;
use App\Jobs\ProcessDatabaseImport;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\Job;
use Illuminate\Support\Facades\Queue;
class JobController extends Controller
{
/**
* Handle Queue Process
*/
public function processQueue()
{
ProcessDatabaseImport::dispatch('database/data/contacts.json')->delay(now()->addMinutes(2));
return view('home');
}
}
已创建作业表,php artisan queue:work 正在运行。
现在,当我在浏览器中转到控制器操作时,“handle()”中的代码会直接执行两次:
日志:
[2019-07-14 13:39:17] local.INFO: Hello world! file: B:\hellodialog\sollicitatieopdracht\database/data/contacts.json
[2019-07-14 13:39:18] local.INFO: Hello world! file: B:\hellodialog\sollicitatieopdracht\database/data/contacts.json
作业的数据库表始终为空。
在我的 .env 文件中:
DB_CONNECTION=mysql
QUEUE_CONNECTION=database
queue.php 配置文件:
return [
'default' => env('QUEUE_CONNECTION', 'database'),
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
'failed' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
有什么遗漏吗?
更新:当我更改 queue.php 中的默认值时,作业被添加到队列中
该作业现在被添加到数据库中两次。我通过访问浏览器中的 URL 来运行此脚本。
【问题讨论】:
标签: php laravel queue jobs laravel-5.8