1. 启动调度器
打开crontab(定时任务)使用如下命令:
vim /etc/crontab
注意:这里不能直接使用
crontab -e
!
底下是唯一一个需要加入到服务器的 Cron 项目:
* * * * * 执行用户 php /path/to/artisan schedule:run >> /dev/null 2>&1
/path/to
是你的项目目录,artisan
执行目录!
2. 添加自定义命令
自定义命令默认存储在
app/Console/Commands
目录中。
自定义命令:
php artisan make:console getNews --command=get:news
执行后会看到getNews.php
命令文件
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(/* 这里支持依赖注入 */){
parent::__construct();
...
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// 这里执行你的业务
...
}
3. 调度定时执行
调度定义在
app/Console/Kernel.php
文件中
- 加入命令:
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\getNews::class,
];
-
schedule
方法定时执行
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// 每10分钟执行 获取新闻
$schedule->command('get:news')->everyTenMinutes();
}
以上这三步执行完成就可以定时执行任务了,并且支持依赖注入!
网友评论