5

I've got a strange issue. I use a custom command to share, via FB api, some url.

Now this command is scheduled to a fixed cron configuration but I would like this to be randomic, maybe between time ranges.

I tried using a random sleep function inside command, but I got strange behavior.

Did anyone already have to face this problem?

alberto-bottarini
  • 1,213
  • 9
  • 21

2 Answers2

7

One solution is to put the code you want to run into a Queued Job, and then delay that job a random amount. For example, this code will run at a random time every hour (the same can easily be extrapolated to random time every day or on some other interval):

$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();
Zane
  • 4,652
  • 1
  • 29
  • 26
4

You can generate random time at beginning.

protected function schedule(Schedule $schedule)
{
    $expressionKey = 'schedule:expressions:inspire';
    $expression = Cache::get($expressionKey);
    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($expressionKey, $expression, Carbon::now()->endOfDay());
    }

    $schedule->command('inspire')->cron($expression);
}
Tegos
  • 405
  • 6
  • 14
Tinpont
  • 41
  • 4
  • Nice approach. I think your cron expression has one too many `*` – BARNZ Mar 04 '18 at 01:50
  • yeah, i tried to fix it to have `* * *`, but stack overflow needs at least 6 characters to be edited :/ – user151496 Jan 21 '21 at 19:28
  • I updated the cron time using after hook. ```$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) . ' * * * *'); });``` – Saiful Islam Feb 26 '21 at 17:38