laravel 定时任务

  laravel中的定时任务真的很方便,在crontab只需要,添加   * * * * php /home/wwwroot/default/app//artisan schedule:run >> /dev/null 2>&1 这个命令就行,这个命令的意思是php以全局命令执行schedule:run ,每分钟扫描一次。

 

  那么laravel中是定时任务是如何实现的呢?

    laravel 中进入app/Console/Kernel.php,一个方法

     protected function schedule(Schedule $schedule)
    {

    }

  这个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\AgentTeamStatistics::class,//该类在Commands中实现
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        \Log::debug('测试日志打印');
     //每分钟执行一次
$schedule->command('statistics:agentTeam') ->timezone('Asia/Shanghai') ->everyMinute()->runInBackground();             //每天凌晨两点执行一次 $schedule->command('statistics:agentTeam') ->timezone('Asia/Shanghai') ->dailyAt('2:00')->runInBackground(); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } }
<?php

namespace App\Console\Commands;


use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计数据';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */


    public function handle()
    {
        //执行具体的业务
    }

}
View Code

 

posted @ 2018-08-05 00:11  queqp  阅读(181)  评论(0)    收藏  举报