laravel 定时

创建任务

使用artisan命令创建一个测试任务

php artisan make:command Test

创建成功

app/Console/Commands/Test.php所在位置

app/Console/Commands/Test.php内容

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

    /**
     * The console command description.
     * 任务描述
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     * 任务功能
     * @return mixed
     */
    public function handle()
    {
        echo 111;
    }

}

调用任务

app/Console/Kernel.php

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     * 定义任务
     * @var array
     */
    protected $commands = [

        \App\Console\Commands\Test::class

    ];

    /**
     * Define the application's command schedule.
     * 调用任务
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();

        $schedule->command('test')->everyMinute();
    }

    /**
     * Register the commands for the application.
     * 注册应用程序的命令
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

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

执行调用

php artisan test

正常输出Test.php中hangle()内容

但是,我继续测试

使用文档那种命名方式

app/Console/Commands/Test.php

protected $signature = 'test:aa';

app/Console/Kernel.php

$schedule->command('test:aa')->everyMinute();

或者

$schedule->command(Test::class)->everyMinute();

执行php artisan test

则会报一个警告

Warning: TTY mode is not supported on Windows platform.

翻译中文意思:警告:Windows平台不支持TTY模式。

在Linux服务器中定义crontab执行任务

添加crontab定时执行任务

crontab -e

* * * * * php目录 laravel项目目录/artisan schedule:run >> /dev/null 2>&1

查看crontab定时执行任务列表

crontab -l

参考:

Linux 的 Crontab 使用:https://www.vpser.net/manage/crontab.html

详细介绍 Laravel 的 Artisan 命令行工具:https://www.bookstack.cn/read/laravel55/artisan.md

https://learnku.com/laravel/wikis/25715

https://www.imooc.com/article/44321

https://segmentfault.com/a/1190000011557313

https://www.sunzhongwei.com/laravel-schedule-a-task-that-is-much-more-convenient-than-linux-system-crontab

http://crocutax.com/blog/laravel-schedule-task

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注




Enter Captcha Here :