Certainly! Laravel Horizon itself does not provide a built-in method to count jobs of a specific class in the queue. However, you can achieve this by directly querying Redis, since Laravel stores queued jobs as serialized payloads in Redis lists.
Here's how you can count jobs of a specific class in a given queue:
- Access the Redis queue list: The queue is stored as a Redis list, typically named
queues:queue-name. - Iterate through the list and count jobs: Deserialize each job payload and check its class.
Here's a sample Artisan command you can use:
php artisan make:command CountQueuedJobs
Then, in your new command (app/Console/Commands/CountQueuedJobs.php):
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class CountQueuedJobs extends Command
{
protected $signature = 'queue:count-jobs {queue} {jobClass}';
protected $description = 'Count jobs of a specific class in a Redis queue';
public function handle()
{
$queue = $this->argument('queue');
$jobClass = $this->argument('jobClass');
$key = "queues:{$queue}";
$count = 0;
$jobs = Redis::lrange($key, 0, -1);
foreach ($jobs as $job) {
$payload = json_decode($job, true);
if (isset($payload['data']['command'])) {
$command = unserialize($payload['data']['command']);
if (get_class($command) === $jobClass) {
$count++;
}
} elseif (isset($payload['job']) && $payload['job'] === $jobClass) {
// For jobs dispatched via the "raw" method
$count++;
}
}
$this->info("Found {$count} jobs of class {$jobClass} in queue {$queue}.");
}
}
Usage:
php artisan queue:count-jobs default App\\Jobs\\MyJob
Notes:
- Replace
defaultwith your queue name. - Replace
App\\Jobs\\MyJobwith your job class (double backslashes for escaping). - This approach works for jobs serialized via Laravel's default queue system.
Caveat:
If you have a very large queue, this operation could be slow, as it loads all jobs into memory.
Let me know if you need a version for a different queue driver or more details!