laravel 6 cannot set delay code for job queue

Viewed 4229

i need help for correct delay code for run the job.. im using laravel 6 and now i doing scraping youtube number of view.

let say that i have table that fill with youtube link. when i do scraping to youtube. we need to add delay time before we go to other link. if we dont make delay it. youtube will block our access. i want to add delay maybe 30 second for each loop.

so what i already trid in my app/Console/Commands/GetYoutube.php file is this

use App\Models\Youtube;
use App\Jobs\GetYoutubeView;
use Carbon\Carbon;
...

public function handle()
    {  

        $youtubes = Youtube::get();
        foreach ($youtubes as $youtube) { 
             GetYoutubeView::dispatch($youtube->link)->delay(Carbon::now()->addSeconds(30));
        }

    }

i tried this code. but still can't add delay 30 seconds for each loop

other think that i add delay code sleep(30); on jobs file. here is what i've done in my jobs app/Jobs/GetYoutubeLink.php

public function handle()
{ 
  sleep(30);
  // Scraping youtube total number of views code
}

but this same. it not delay 30 second for each loop. what is the correct delay code for this.

please help. what is correct delay code in my case.

1 Answers

When you call dispatch the job is dispatched. You are calling the delay after that. You should create the job and delay the job before dispatching.

$youtubes = Youtube::get();
$start = Carbon::now();

foreach ($youtubes as $youtube) { 
    $job = new GetYoutubeView($youtube->link);
    $job->delay($start->addSeconds(30));

    dispatch($job);
}

EDIT

You where calling multiple now dates before, you should only create one date, and keep adding 30 seconds to it.

Related