Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 243
alberto-bottarini Avatar asked Feb 07 '23 20:02

alberto-bottarini


1 Answers

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();
like image 58
Zane Avatar answered Feb 10 '23 09:02

Zane