传统的计划任务是使用linux的crontab
,每次对计划任务进行修改都要上服务器处理,不方便且不安全。laravel的命令调度器允许我们通过简单的配置即可实现计划任务功能。
场景假设:每分钟执行将当前时间戳写入文本中
实现流程如下:
新建artisan命令
$ php artisan make:command WriteTime --command=write:time-stamp
Console command created successfully.
--command 是指定 Artisan 调用的命令
以上指令生成了 app/Console/Commands/WriteTime.php
,对该文件进行以下修改:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class WriteTime extends Command
{
protected $signature = 'write:time-stamp';
protected $description = '将时间戳写入文件';
public function __construct()
{
parent::__construct();
}
public function handle()
{
// 在命令行打印信息
$this->info('开始执行...');
file_put_contents('./write_time.txt', time() . "\n", FILE_APPEND);
$this->info('执行结束...');
}
}
执行 php artisan list
可查看新增的指令:

手动执行一次
$ php artisan write:time-stamp
开始执行...
执行结束...
查看运行结果:
$ cat ./write_time.txt
1553669521
设置成计划任务
laravel的调度依然是需要借助crontab,但只需要设置一次即可
新增crontab
$ crontab -e
将以下内容加到crontab
# 注意将程序路径改为你自己的项目路径
* * * * * php artisan schedule:run >> /dev/null 2>&1
系统的 Cron 已经设定好了,现在 Cron 软件将会每分钟调用一次 Laravel 命令调度器,当 schedule:run
命令执行时, Laravel 会评估你的计划任务并运行预定任务。

app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
// 每分钟执行一次
$schedule->command('write:time-stamp')->everyMinute();
}
接下来,每分钟都会调用 write:time-stamp
指令
网友评论