Search code examples
laravelscheduling

Laravel dispatching Queues at set time


I am currently dispatching queued jobs to send API Events instantly, in busy times these queued jobs need to be held until overnight when the API is less busy, how can I hold these queued jobs or schedule them to only run from 01:00am the following day.

the Queued Job call currently looks like:

EliQueueIdentity::dispatch($EliIdentity->id)->onQueue('eli');

there are other jobs on the same queue, all of which will need to be held in busy times


Solution

  • Use delay to run job at a certain time.

    EliQueueIdentity::dispatch($EliIdentity->id)
        ->onQueue('eli')
        ->delay($this->scheduleDate());
    

    Helper for calculating the time, handling a edge case between 00:00 to 01:00, where it would delay it a whole day. While not specified how to handle busy, made an pseudo example you can implement.

    private function scheduleDate()
    {
        $now = Carbon::now();
    
        if (! $this->busy()) {
            return $now;
        }
    
        // check for edge case of 00:00:00 to 01
        if ($now->hour <= 1) {
            $now->setTime(1, 0, 0);
            return $now;
        }
    
        return Carbon::tomorrow()->addHour();
    }