laravel 设置定时任务(任务调度)

创建定时任务

crontab -e

#添加代码
* * * * * /usr/bin/php7.0 /var/www/html/laravel/artisan schedule:run >> /dev/null 2>&1

注意:/usr/bin/php7.0为你的php位置 ,* * * * *分别代表 分 时 日 月 周 (定时任务的时间) /var/www/html/laravel/为你的项目位置

查看定时任务

crontab -l

定义调度

在App\Console\Commands下创建Test.php

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
use Log;

class Test extends Command {

    protected $name = 'test';//命令名称

    protected $description = '测试'; // 命令描述,没什么用

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        log::info('test');
            // 功能代码写到这里
    }

}

编辑 app/Console/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\Test::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('test')//Test.php中的name
                 ->everyFiveMinutes();//每五分钟执行一次
    }

}

PS:如果有多个定时任务,只需要参照test.php再次生成一个,Kernel.php中的$commands数组中再添加新加的类,schedule中$schedule->command('新name')->everyFiveMinutes();即可

常用:

->cron('* * * * *');    在自定义Cron调度上运行任务
->everyMinute();    每分钟运行一次任务
->everyFiveMinutes();   每五分钟运行一次任务
->everyTenMinutes();    每十分钟运行一次任务
->everyThirtyMinutes(); 每三十分钟运行一次任务
->hourly(); 每小时运行一次任务
->daily();  每天凌晨零点运行任务
->dailyAt('13:00'); 每天13:00运行任务
->twiceDaily(1, 13);    每天1:00 & 13:00运行任务
->weekly(); 每周运行一次任务
->monthly();    每月运行一次任务
->monthlyOn(4, '15:00');    每月4号15:00运行一次任务
->quarterly();  每个季度运行一次
->yearly(); 每年运行一次
->timezone('America/New_York'); 设置时区

猜你喜欢

转载自www.cnblogs.com/www-php/p/9242052.html