[英]how to change laravel jobs time
我正在为客户开发应用程序,他想在特殊时间开始一些工作,我必须在工作中运行它,对吗? 例如,他想发布一个帖子有 2 个状态已发布或等待并在发送页面,他可以设置发布帖子的时间我如何在工作中开发这个?
ScanJob::dispatch($property->Name, $property->Owner, $Scan->id)->delay(Carbon::now()->addHour(Carbon::now()->diffInHours($Time)));
这是我第一次尝试以小时为单位获取差异时间并从延迟中添加它
基本上有两种方法可以解决您的问题:
创建一个 Laravel Artisan 命令(您也可以使用 Laravel 提供的其他方法,但我发现 Artisan 更有趣且更灵活,有助于避免返工)并相应地安排它。
创建一个排队作业并在稍后调度它,但它有一些限制,例如,Amazon SQS 队列服务的最大延迟时间为 15 分钟。
现在,要做什么:
现在是有趣的部分。 注意:您不必担心,Laravel 将为您执行大部分步骤。 为了不跳过知识,我提到了每一步。
第 1 步:运行以下命令以创建 Artisan 控制台命令(请记住位于项目的根路径中。):
php artisan make:command PublishSomething
该命令现在可用于app/Console/Commands
的进一步开发。
第 2 步:您将在 Class 中看到一个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 步:我们的 function 运行良好。 现在我们将安排命令。 在app/Console
中你会找到一个文件Console.php
,在我们的例子中,这个 class 负责所有的任务调度注册。
<?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');
}
}
注意这里的计划 function,这是我们将添加计划逻辑的地方。
第 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 分钟一次。
您可以了解有关Laravel Artisan 命令和Laravel 任务调度的更多信息。
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.