Hey fellow Laravel!
I've been working on a project where I need to generate jobs in a loop, but I've encountered a common problem:
API rate limits. Every time I dispatch a job that calls an external API, I run into the dreaded "too many requests" error from the API server.
To tackle this issue, I thought about adding a delay between each job. My initial idea was to use the loop index and delay each job by a certain amount of time. However, I faced a challenge when dealing with nested jobs – the loop index kept resetting to zero.
Here's a snippet of what I've been working on:
foreach ($milestones as $index => $milestone) {
ProjectMilestones::dispatch($milestone['id'])
->onQueue('teamleader')
->delay(now()->addSeconds($index * 50));
}
$index log :
0
1
2
3
4
5
6
0
1
2
0
1
2
3
6
5
4
7
As you can see, the $index variable resets to zero when logging it within the loop of another job. This inconsistency in index values prevents me from implementing a consistent delay between jobs.
So, my question is: Is it possible in Laravel to make a delay dependent on the previous job's completion time?
I'd appreciate any insights or suggestions on how to solve this issue effectively. Let's brainstorm together!
Thanks,