扣丁学堂PHP培训简述如何实现Laravel框架定时任务

2019-04-03 15:08:53 1284浏览

Laravel框架定时任务有多少的小伙伴知道呢?本篇文章扣丁学堂PHP培训小编给大家分享Laravel框架定时任务2种实现方式,文中有详细的代码列出供大家参考,希望对小伙伴们有所帮助。



PHP培训



第一


1、生成一个commands文件


> php artisan make:command test


2、打开文件进行修改


laravel\App\Console\Commands\test.php


<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class test extends Command
{
 /**
  * The name and signature of the console command.
  *
  * @var string
  */
 protected $signature = 'test:insert'; // php artisan list 中将会生成 "php artisan test:insert " 指令
 /**
  * The console command description.
  *
  * @var string
  */
 protected $description = 'insert Test table some test data'; // 对上面指令的描述
 /**
  * Create a new command instance.
  *
  * @return void
  */
 public function __construct()
 {
  parent::__construct();
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
  // 编写你要的定时任务执行的代码!
  # eg
 Log::info('test');
 }
}

> php artisan list 查看


Python视频


3、然后修改: laravel\app\Console\Kernel.php 文件


<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
 protected $commands = [
  // 参考手册 新加
  \App\Console\Commands\test::class,
 ];
 // 定义应用的命令调度
 protected function schedule(Schedule $schedule)
 {
   // 新加 每分钟执行一次
  $schedule->command('test:insert')->everyMinute();
 }
 protected function commands()
 {
  $this->load(__DIR__.'/Commands');
  require base_path('routes/console.php');
 }
}


4、启用计划任务:在服务器中加入到计划任务 crontab -e


注意这里的 path 是你的laravel项目根目录的 绝对路径!, 然后加上后面的 artisan 到结尾的字符串


* * * * * php /path/artisan schedule:run >> /dev/null 2>&1

* * * * * php /code/src/laravel/artisan schedule:run >> /dev/null 2>&1


5、打开日志文件查看


laravel\storage\logs\laravel.log



二种


使用 shell脚本执行


因为 php artisan list 可以查看到 执行指令 test:insert所以可以考虑用 .sh 脚本执行,还是类似上面 crontab -e编写


1、先编写 .sh 脚本 laravel/test.sh 放在项目某个位置,文件内写入


php artisan test:insert


上面指令在命令行手动每执行一次就可以触发一次编写的程序,相当于给 laravel.log 写入一次 test


2、使用 crontab -e 编写 执行 第一步写的 test.sh 脚本


* * * * * laravel/test.sh


以上两种均可看到 laravel.log 日志


Python学习


想要了解更多关于PHP开发方面内容的小伙伴,请关注扣丁学堂PHP培训官网、微信等平台,扣丁学堂IT职业在线学习教育有专业的PHP讲师为您指导,此外扣丁学堂老师精心推出的PHP视频教程定能让你快速掌握PHP从入门到精通开发实战技能。扣丁学堂PHP技术交流群:374332265。


扣丁学堂微信公众号                          Python全栈开发爬虫人工智能机器学习数据分析免费公开课直播间


【关注微信公众号获取更多学习资料】         【扫码进入Python全栈开发免费公开课】



查看更多关于“php培训资讯”的相关文章>>



标签: PHP培训 PHP基础教程 PHP学习视频 PHP教学视频 PHP入门教程 PHP教程视频 PHP在线学习 PHP在线视频 PHP在线教程 扣丁学堂PHP培训

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号