来自 Laravel 的示例 documentation :
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
DB::table('recent_users')->delete();
})->daily();
}
注意 daily 函数。
我想不通,它怎么知道什么时候开始? 它总是在午夜开始还是在随机 float 时间开始?
我试着阅读源代码:
/**
* 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));
}
最后我完全迷路了。知道它的行为方式吗?
最佳答案
快速看起来似乎很复杂,但总的来说:
\Illuminate\Console\Scheduling\Event
你的类(class):
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 等运行,这就是为什么您应该将调度程序设置为每分钟运行一次。
关于php - Laravel schedule - 每小时,每天 - 了解何时开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47224505/