1 回答

TA贡献1821条经验 获得超4个赞
基本上有两种方法可以解决您的问题:
创建一个 Laravel Artisan 命令(您也可以使用 Laravel 提供的其他方法,但我发现 Artisan 更有趣且更灵活,有助于避免返工)并相应地安排它。
创建一个队列作业并在稍后派发它,但它有一些限制,例如 Amazon SQS 队列服务的最大延迟时间为 15 分钟。
现在,要做的是:
在我看来,您应该使用解决方案 1,因为它更灵活并且给您更多的控制权。
队列用于两件事。首先,理想情况下,您要执行的任务应在接下来的 30-45 分钟内完成。其次,任务是时间密集型的,您不想因此而阻塞线程。
现在是有趣的部分。注意:您不必担心,Laravel 会为您执行大部分步骤。为了不跳过知识,我提到了每一步。
第 1 步:运行以下命令创建一个 Artisan 控制台命令(记住要在项目的根路径中。):
php artisan make:command PublishSomething
该命令现在可用于进一步开发,网址为app/Console/Commands
。
第 2 步handle
:您将在类中看到一个方法,如下所示,这是您所有逻辑所在的地方。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class PublishSomething extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'something:publish';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publishes something amazing!';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
}
}
第 3 步:让我们在 handle 方法中添加一些逻辑
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Publishing something cool!');
// you can add your own custom logic here.
}
第 4 步:添加逻辑后,现在我们需要对其进行测试,您可以这样做:
php artisan something:publish
第 5 步:我们的功能运行正常。现在我们将安排命令。在里面app/Console你会发现一个文件Console.php,这个类负责所有的任务调度注册,在我们的例子中。
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
注意这里的调度函数,这是我们将添加调度逻辑的地方。
第 6 步:现在我们将安排我们的命令每 5 分钟运行一次。你可以很容易地改变时间段,Laravel 提供了一些预制的频率选项,你也有自己的自定义时间表。
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('something:publish')->everyFiveMinutes(); // our schedule
}
第 7 步:现在,Laravel 的任务调度程序本身依赖于 Cron。因此,要启动计划,我们将以下文件添加到我们的 crontab。
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
就是这样!我们完了。您已经创建了自己的自定义命令并计划每 5 分钟执行一次。
- 1 回答
- 0 关注
- 136 浏览
添加回答
举报