Laravel 定时任务

2017-07-26 11:57:00

在 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 还没研究过实现方法。


  • 2018-02-23 14:22:50

    mysql的yearweek 和 weekofyear函数

    例如 2010-3-14 ,礼拜天 SELECT YEARWEEK('2010-3-14') 返回 11 SELECT YEARWEEK('2010-3-14',1) 返回 10 其中第二个参数是 mode ,具体指的意思如下: Mode First day of week Range Week 1 is the first week … 0 Sunday 0-53 with a Sunday in this year 1 Monday 0-53 with more than 3 days this year 2 Sunday 1-53 with a Sunday in this year 3 Monday 1-53 with more than 3 days this year 4 Sunday 0-53 with more than 3 days this year 5 Monday 0-53 with a Monday in this year 6 Sunday 1-53 with more than 3 days this year 7 Monday 1-53 with a Monday in this year 2.

  • 2018-02-23 17:20:44

    Mysql数据库If语句的使用

    MySQL的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为表达式使用:

  • 2018-02-24 10:16:36

    Java工具类之Apache的Commons Lang和BeanUtils

    Apache Commons包估计是Java中使用最广发的工具包了,很多框架都依赖于这组工具包中的一部分,它提供了我们常用的一些编程需要,但是JDK没能提供的机能,最大化的减少重复代码的编写。