Laravel使用command在Linux系统中跑定时任务

一、前言#

在 windows 系统中我们通常使用系统自带的计划任务来执行定时任务,在 Linux 系统中我们通常配合 crontab 使用 shell 脚本或者访问url 来完成定时任务,laravel 的 command 在 Linux 中使用很方便,并且 laravel 中的 command 也提供了多种时间调度方法。

二、新建 command 文件#

执行:php artisan make:command Luckinman 命令,会在 app\console\commands 命令下生成一个 Luckinman.php 的文件。

在这里插入图片描述

三、写业务逻辑#

其中:

  • $signature 为这个类定义一个执行名称。
  • $description 为这个类增加信息描述。
  • handle 方法中写自己的业务逻辑。
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Model\Student;
use Illuminate\Support\Facades\Log;

class Luckinman extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'this is test';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            Log::info('测试定时任务:'.date('Y-m-d H:i:s'));
        }catch (\Exception $e){
            Log::info($e->getMessage());
        }
    }
}

在控制台中执行该类的 handle 方法,使用命令:php artisan test 即可。其中 test$signature 中定义的名称。

四、框架中配置调度频率#

commands 同级目录下有一个 kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\Luckinman::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('test')->everyFiveMinutes();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

$commands 属性里引入我们创建的定时测试类,并在 schedule 方法中进行配置任务调度时间。

其中 everyFiveMinutes 代表每分钟执行一次。

五、Linux 中开启任务调度#

例如,一分钟执行一次:

* * * * * /www/server/php/73/bin/php /www/wwwroot/lars.wangchuangcode.cn/artisan schedule:run >> /dev/null 2>&1

其中,/www/server/php/73/bin/php 是我 php 的运行配置文件所在路径,根据自己的填写。/www/wwwroot/lars.wangchuangcode.cn/ 是我的项目根目录。

至此,command 定时调度配置成功。

如果想把 crontab 每次运行记录到日志中,在后面指定一个文件即可:* * * * * /www/server/php/73/bin/ php /www/wwwroot/lar.wangchuangcode.cn/artisan schedule:run >> /dev/null 2>&1 >> /www/wwwroot/1.txt

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。