Last active
April 29, 2020 17:26
-
-
Save deviationist/125b4e91431db67f9d684e792a9a0002 to your computer and use it in GitHub Desktop.
This function will help you determine whether an item is already added to the queue or not. Note: only works when using the database queue driver.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Example usage: | |
// The payload of the job | |
$userQueueItem = [ | |
'id' => 5, | |
'username' => 'user', | |
'email' => 'user@mail.com', | |
]; | |
// Pass the job name (including namespace), the user queue item we would like to check if is already added to the queue, and then the function closure which will match each queue item against our user queue item | |
$alreadyAddedToQueue = itemAlreadyAddedToQueue('App\Jobs\CalculateLoyaltyPoints', $userQueueItem, function($jobParameters, $userQueueItem) { | |
return $jobParameters['id'] === $userQueueItem['id']; | |
}); | |
if ( ! alreadyAddedToQueue ) { | |
// Only dispatch job if the user queue item is not already in the queue | |
CalculateLoyaltyPoints::dispatch($userQueueItem); | |
} | |
*/ | |
if ( ! function_exists('itemAlreadyAddedToQueue') ) | |
{ | |
/** | |
* Check if an item is already in the queue (only works with the Database queue driver). | |
* | |
* @param $item | |
* @param $closure | |
* @param $jobName | |
* | |
* @return bool | |
*/ | |
function itemAlreadyAddedToQueue($item, $closure, $jobName = false) | |
{ | |
$alreadyAdded = false; | |
$queue = \DB::table(config('queue.connections.database.table'))->get(); | |
$queue->each(function($queueItem) use ($item, $closure, $jobName, &$alreadyAdded) { | |
// Decode the queue data | |
$decodedJobPayload = json_decode($queueItem->payload,true); | |
// This is not the queue item we are looking for | |
if ( $jobName !== false && $decodedJobPayload['displayName'] !== $jobName ) { | |
return true; // Continue | |
} | |
// Get job parameters | |
$data = data_get($decodedJobPayload, 'data', []); | |
$jobParameters = unserialize(data_get($data, 'command', '')); | |
// Could not get any parameters | |
if ( ! $jobParameters ) { | |
return true; // Continue | |
} | |
// Determine result with closure | |
if ( is_callable($closure) && $closure($jobParameters, $item) === true ) { | |
$alreadyAdded = true; | |
return false; // Break loop | |
} | |
}); | |
return $alreadyAdded; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment