laravel schedule command at random time
Asked Answered
L

3

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?

Lutyens answered 4/2, 2016 at 11:37 Comment(0)
J
9

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();
Jez answered 18/11, 2019 at 5:43 Comment(0)
L
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);
}
Lushy answered 4/1, 2017 at 13:51 Comment(3)
Nice approach. I think your cron expression has one too many *Humes
yeah, i tried to fix it to have * * *, but stack overflow needs at least 6 characters to be edited :/Ceiba
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) . ' * * * *'); });Joubert
W
0

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

Worsham answered 27/2 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.