Laravel 定时任务

admin 2019-3-20 490

在 php 中使用定时器是一件不太简单的事情,之前大概只能通过 cron 来实现定时任务。但是在 Laravel5 中,定时任务将会变得很简单。

Laravel Schedule

这个是 Laravel5 中新增加的特性之一。在 Laravel5 中,进入到 app/Console/Kernel.php 中,可以看到以下代码:

     protected function schedule(Schedule $schedule)
    {
        $schedule->command('inspire')
                 ->hourly();
    }

这个 schedule 方法就是定时任务执行的关键,我们可以将所有的定时任务都放到其中,其中, Laravel 提供了诸多的方法来控制任务执行的时间间隔,例如:

    $schedule->command('foo')->everyFiveMinutes();

    $schedule->command('foo')->everyTenMinutes();

    $schedule->command('foo')->everyThirtyMinutes();

    $schedule->command('foo')->mondays();

    $schedule->command('foo')->tuesdays();

    $schedule->command('foo')->wednesdays();

    $schedule->command('foo')->thursdays();

    $schedule->command('foo')->fridays();

    $schedule->command('foo')->saturdays();

    $schedule->command('foo')->sundays();

我们既可以通过创建 Command 来作为任务来执行,也可以使用闭包函数来作为任务:

    $schedule->call(function()
    {
        //TODO ...

    })->hourly();

就这样,要执行的任务就可以简单的创建。

启动 Schedule

在定义完以上的任务之后,可以通过 php artisan schedule:run 来执行这些任务,但是,这个任务执行起来后,需要不断的执行这个这个命令定时器才能不断的运行,所以就需要 linux 的系统功能的帮助,在命令行下执行下面的命令:

    crontab -e

执行完以上的命令之后,会出现一个处于编辑状态的文件,在文件中填入以下内容:

    * * * * * php /path/to/artisan schedule:run

然后保存,关闭。上面命令的含义是每隔一分中就执行一下 schedule:run命令。这样一来,前面定义的任务就可以不断的按照定义的时间间隔不断的执行,定时任务的功能也就实现了。

注:这个仅仅是在 linux 平台上,windows 请用计划任务。


最新回复 (0)
全部楼主
返回
发新帖
老师机论坛