laravel - 任务调度

1、在定时任务crontab建立定时任务 crontab -e 或者 vim /etc/crontab

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

* * * * * /usr/local/php/bin/php /www/wwwroot/html/artisan schedule:run >> /dev/null 2>&1

2、创建单个执行任务。
这个是创建执行文件, 修改 TestTask 的 signature (eg: testtask {--date=}),在 handle() 中编写业务逻辑

php artisan make:command TestTask
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'TestTask->insertData';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::table('test')->insert(array('name' => '小明是' . date("Y-m-d H:i:s")));
    }
}

3、配置定时任务
修改 app/Console/Kernel.php文件,添加此次添加的任务在commands,同时修改schedule函数

<?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\LogTask::class,
        \App\Console\Commands\TestTask::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
//        $schedule->call(function () {
//            DB::table('test')->insert(array('name' => 'test' . date("Y-m-d H:i:s")));
//        })->everyMinute();

        $schedule->command("TestTask:insertData")->everyMinute();
        $schedule->command("LogTask:logNote")->everyFiveMinutes();
    }

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

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

4、执行任务

php artisan Schedule:run

单独执行某一条任务

php artisan TestTask:insertData
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。