alberto-bottarini
alberto-bottarini

Reputation: 1231

laravel schedule command at random time

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?

Upvotes: 6

Views: 2869

Answers (3)

Skywarth
Skywarth

Reputation: 823

I've created a laravel package for scheduling commands on random intervals. It's super simple to use and provides wide range of random time and random date scheduling capabilities:

$schedule->command('your-command-signature:here')->daily()->atRandom('08:15','11:42');
$schedule->command('your-command-signature:here')
   ->weekly()
   ->randomDays(RandomDateScheduleBasis::WEEK,[Carbon::FRIDAY,Carbon::Tuesday,Carbon::Sunday],1,2)
   ->atRandom('14:48','16:54');

I believe it is exactly what you're looking for, so go ahead and give it a try.

Just install the package and you're good to go: composer require skywarth/chaotic-schedule

https://github.com/skywarth/chaotic-schedule

Upvotes: 0

Tinpont
Tinpont

Reputation: 41

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);
}

Upvotes: 4

Zane
Zane

Reputation: 4752

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();

Upvotes: 9

Related Questions