【问题标题】:laravel schedule command at random timelaravel schedule 命令在随机时间
【发布时间】:2016-05-14 00:07:49
【问题描述】:

我有一个奇怪的问题。 我使用自定义命令通过 FB api 共享一些 url。

现在这个命令被安排到一个固定的 cron 配置,但我希望这是随机的,可能在时间范围之间。

我尝试在命令中使用随机睡眠功能,但出现了奇怪的行为。

有人已经不得不面对这个问题了吗?

【问题讨论】:

    标签: laravel random laravel-scheduler


    【解决方案1】:

    一种解决方案是将要运行的代码放入排队作业中,然后随机延迟该作业。例如,此代码将在每小时随机时间运行(同样可以很容易地推断为每天或其他时间间隔的随机时间):

    $schedule
      ->call(function () {
        $job = new SomeQueuedJob();
        // Do it at some random time in the next hour.
        $job->delay(rand(0, 60 * 59));
        dispatch($job);
      })
      ->hourly();
    

    【讨论】:

      【解决方案2】:

      您可以在开始时生成随机时间。

      protected function schedule(Schedule $schedule)
      {
          $expression = \Cache::get('schedule:expressions:inspire');
          if (!$expression) {
              $randomMinute = random_int(0, 59);
      
              // hour between 8:00 and 19:00
              $hourRange = range(8, 19);
              shuffle($hourRange);
              // execute twice a day
              $randomHours = array_slice($hourRange, 0, 2);
      
              $expression = $randomMinute . ' ' . implode($randomHours, ',') . ' * * * *';
              \Cache::put('schedule:expressions:inspire', $expression, Carbon::now()->endOfDay());
          }
      
          $schedule->command('inspire')->cron($expression);
      }
      

      【讨论】:

      • 不错的方法。我认为您的 cron 表达式有太多 *
      • 是的,我尝试将其修复为具有* * *,但堆栈溢出至少需要编辑 6 个字符:/
      • 我使用 after hook 更新了 cron 时间。 $fb = Cache::get('facebook_cron'); if ($fb) {Cache::forever('facebook_cron', '*/30 * * * *');} $schedule->command('facebook:post')->cron($fb)->after(function () { Cache::forever('facebook_cron', '*/' . rand(20, 40) . ' * * * *'); });
      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 2022-12-15
      • 2019-07-21
      • 2016-04-05
      • 1970-01-01
      • 2017-12-06
      • 2021-01-06
      • 2022-01-12
      相关资源
      最近更新 更多