前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Laravel框架定时任务2种实现方式示例

Laravel框架定时任务2种实现方式示例

作者头像
砸漏
发布2020-10-21 15:43:25
8200
发布2020-10-21 15:43:25
举报
文章被收录于专栏:恩蓝脚本

本文实例讲述了Laravel框架定时任务2种实现方式。分享给大家供大家参考,具体如下:

第一种

1、生成一个commands文件

代码语言:javascript
复制
  php artisan make:command test

2、打开文件进行修改

laravel\App\Console\Commands\test.php

代码语言:javascript
复制
<?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 查看

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

代码语言:javascript
复制
<?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 放在项目某个位置,文件内写入

代码语言:javascript
复制
php artisan test:insert

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

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

* * * * * laravel/test.sh

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

更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档