中文说明
上面中文说明其实已经很清楚了,把我在做的过程中的坑记录下来。
- 创建 Command
参考
要创建一个新的命令,可以使用 make:command 命令。这个命令会创建一个命令类并存放在 app/Console/Commands 目录。 不必担心不存在这个目录,运行 make:command 命令时会首先创建这个目录。生成的命令将会包括所有默认存在的属性和方法:
php artisan make:command SendEmails
demo:
<?php
/*
* This file is part of PHP CS Fixer.
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Console\Commands;
use App\Repositories\FeedRepository;
use Illuminate\Console\Command;
class CacheFeeds extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'feed:cache';
/**
* The console command description.
*
* @var string
*/
protected $description = 'feeds 缓存';
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
set_time_limit(60 * 30);
$feed = new FeedRepository();
$feed->cacheFeeds();
}
}
新增成功后,执行 php artisan list
可以见到刚刚创建的command:feed:cache
- 将新增的command 添加到schedule
修改./app/Console/Kernel.php,添加$commands
,在schedule
function 中定义任务调度的执行频率和输出log等配置。需要注意的是command('feed:cache')
输入的是在command中定义的$signature
。
<?php
/*
* This file is part of PHP CS Fixer.
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
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 = [
\App\Console\Commands\CacheFeeds::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
*/
protected function schedule(Schedule $schedule)
{
$filePath = storage_path().'/logs/cache.log';
$schedule->command('feed:cache')
->appendOutputTo($filePath)
->cron('*/15 * * * *')
->after(function () {
echo datetime().' feed cache completed! '.PHP_EOL;
})
;
}
/**
* Register the Closure based commands for the application.
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
- 在cronjob中添加
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
/path/to/artisan
就是项目地址,例如 /home/laravel-project/artisan
添加后重启crontab,service cron restart
,到执行时间会在输出的log中见到。
注意点:
- crontab 的命令建议要手打,不要复制粘贴,
>> /
可能会被转义 - 可以手动执行
php artisan feed:cache
看下单个命令有无问题 - 手动执行
php artisan schedule:run
会出no command ready to run
的提示,因为schedule
的执行机制是每分钟执行一次,当系统当前时间除以schedule
的循环时间是整数时才会执行 -
schedule:run
不能放入supervisor
执行,因为每次执行后会自动退出,导致supervisor Failed
退出