基本用法
生成命令
php artisan make:command AreYouOK
5.2 及之前的版本,此命令为 `php artisan make:console xxx`
编辑命令
编辑 `app/Console/Commands/AreYouOK.php` 文件,修改如下几处:
... ...
protected $signature = 'areyou:ok'; // 命令名称
protected $description = '雷军,科技圈最会唱歌的男人'; // 命令描述,没什么用
public function __construct()
{
parent::__construct();
// 初始化代码写到这里,也没什么用
}
public function handle()
{
// 功能代码写到这里
}注册命令
编辑 `app/Console/Kernel.php` 文件,将新生成的类进行注册:
protected $commands = [ \App\Console\Commands\AreYouOK::class, ];
编写调用逻辑:
protected function schedule(Schedule $schedule)
{
$schedule->command('areyou:ok')
->timezone('Asia/Shanghai')
->everyMinute();
}上面的逻辑是每分钟调用一次。Laravel 提供了从一分钟到一年的各种长度的时间函数,直接调用即可。
把这个 Laravel 项目注册到系统的 cron 里
编辑 `/etc/crontab` 文件,加入如下代码:
复制代码 代码如下:
* * * * * root /usr/bin/php /var/www/xxxlaravel/artisan schedule:run >> /dev/null 2>&1
上面一行中的 `/var/www/xxxlaravel` 需要改为实际的路径。
fire
重启 cron 激活此功能:`systemctl restart crond.service`,搞定!
下一篇:PHP如何实现计算抽奖概率算法