CRON作业-为不同时区安排Laravel命令-为不同地区进行管理

我正在使用Laravel 5.8,我想自动生成应在周一至周日自动生成的发票。 每个星期天晚上23:59:00

假设我有

“根据区域时区为23:59:00”。

每个商店都与一个地区相关,从地区表中您可以找到时区。

问题 我应该如何设置CRON作业,以便可以根据将从表中获取的时区列表自动生成发票?

评论
  • 哭着高兴%
    哭着高兴% 回复

    You can use the timezone() method in your task Schedulding

    Using the timezone method, you may specify that a scheduled task's time should be interpreted within a given timezone:

    $schedule->command('report:generate')
             ->timezone('America/New_York')
             ->at('02:00')
    
  • 纠缠
    纠缠 回复

    我有两个建议;

    if you want it to be static, define each command with the corresponding timezone from your database. Different timezones may have same time such as Europe/Amsterdam and Europe/Berlin

    $schedule->command('generate:report')->timezone('one-of-the-timezone')->at('23:59');
    $schedule->command('generate:report')->timezone('another-timezone')->at('23:59');
    $schedule->command('generate:report')->timezone('yet-another-timezone')->at('23:59');
    $schedule->command('generate:report')->timezone('some-other-timezone')->at('23:59');
    

    If you want it to be dynamic, make it run every 59. min hourly and try to match it with the timezones via using hour.

    $schedule->command('generate:report')->hourlyAt(59);
    

    在命令类中;

    public function handle(TimezoneRepository $timezoneRepository)
    {
        $timezones = $timezoneRepository->getUniqueTimezones(); // the unique timezones in your database - cache if you want
    
        foreach ($timezones as $timezone) {
            $date = Carbon::now($timezone); // Carbon::now('Europe/Moscow'), Carbon::now('Europe/Amsterdam') etc..
    
            if ($date->hour === 23) { // you are in that timezone
                $currentTimezone = $date->getTimezone();
                dispatch(new ReportMaker($currentTimezone)); // dispatch your report maker job
            }
        }
    }
    

    With the dynamic one, you will hit to multiple timezones at one iteration(when generate:report is executed) as i said at then beginning.

    • 可能的缺陷之一可能是;如果执行获取时区等的时间超过1分钟,则您可能是在00:00而不是23:59。最好以异步方式计算报表并缓存时区列表,以免在执行此循环时遇到问题。
    • 另一个可能的缺陷;

    According to wiki;

    某些区域会相差30或45分钟(例如,纽芬兰标准时间为UTC-03:30,尼泊尔标准时间为UTC + 05:45,印度标准时间为UTC + 05:30,缅甸标准时间为UTC + 06: 30)。

    如果您想涵盖其中任何一个,那么最好执行这样的命令

    $schedule->command('generate:report')->cron('14,29,44,59 * * * *');
    

    并进行小时和分钟的比较,例如;

    $date->hour === 23 && $date->hour === 59