4

Laravel文档中的示例:

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        DB::table('recent_users')->delete();
    })->daily();
}

注意日常 功能。

我想不通,它如何知道什么时候开始?它总是在午夜或随机浮动时间开始吗?

我试图阅读源代码:

/**
 * Schedule the event to run daily.
 *
 * @return $this
 */
public function daily()
{
    return $this->spliceIntoPosition(1, 0)
                ->spliceIntoPosition(2, 0);
}

所以我检查了 spliceIntoPosition 函数:

    /**
 * Splice the given value into the given position of the expression.
 *
 * @param  int  $position
 * @param  string  $value
 * @return $this
 */
protected function spliceIntoPosition($position, $value)
{
    $segments = explode(' ', $this->expression);

    $segments[$position - 1] = $value;

    return $this->cron(implode(' ', $segments));
}

最终我完全迷路了。任何想法它的行为方式?

4

2 回答 2

2

快速查看似乎很复杂,但总的来说:

\Illuminate\Console\Scheduling\Event

你有课:

public $expression = '* * * * * *';

运行daily()方法时,它变为:

public $expression = '0 0 * * * *';

稍后在确定是否应该运行此事件时isDue(),同一类中有方法,它最终调用:

CronExpression::factory($this->expression)->isDue($date->toDateTimeString())

在同一个类CronExpression中,您有isDue()一个最终getRunDate()将从同一个类运行的方法,该方法计算下一次应该运行该命令的时间,最后将其与当前时间进行比较:

return $this->getNextRunDate($currentDate, 0, true)->getTimestamp() == $currentTime;

所以为我回答你的问题,它似乎会在精确的分钟内运行,所以当你使用例如每 5 分钟时,它将在 1:00、1:05、1:10 等运行,这就是为什么你应该有调度程序设置为每分钟运行一次。

于 2017-11-10T14:50:02.157 回答
1

Laravel 文档准确指定每天运行的时间

daily();    // Run the task every day at midnight

基本上在你添加之后

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

到您的 crontab Laravel 将每分钟调用一次调度程序,并且在每次调用时都会评估您的计划任务并运行到期的任务。

我建议阅读有关cron以及规则如何工作的内容,这将使您了解为什么在此处调用函数 spliceIntoPosition() 以及它的作用。

示例 cron 选项卡记录

* * * * * // will run every single minute
0 * * * * // will run every single hour at 30 [ 0:00, 1:00 ...] 
30 1 * * * // will run every single day at 1:30 [ Mon 1:30, Tue 1:30 ...] 

因此,在 spliceIntoPosition() 调用之后的 daily() 中,我们得到:

"0 0 * * *" // which will be called at 0:00 every single day
于 2017-11-10T14:42:42.387 回答