To measure the number of jobs of a specific type currently on the queue managed by Laravel Horizon, you can leverage Laravel's built-in queue and Horizon functionalities. Here’s a step-by-step solution to achieve this:
Step 1: Use Horizon's Metrics
Laravel Horizon provides metrics that can be used to monitor the jobs. You can use the Horizon::stats() method to get an overview of the queue status.
Step 2: Fetch Specific Job Type Count
To count the number of jobs of a specific type, you can use the Queue facade to inspect the jobs in the queue. However, Horizon does not provide a direct way to filter jobs by type. Instead, you can use Redis commands to filter and count the jobs.
Step 3: Custom Command to Count Jobs
You can create a custom Artisan command to count the jobs of a specific type. Here’s an example of how you can achieve this:
Create a Custom Artisan Command
-
Generate a new Artisan command:
php artisan make:command CountSpecificJobs -
Implement the command logic in
app/Console/Commands/CountSpecificJobs.php:<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Redis; class CountSpecificJobs extends Command { protected $signature = 'jobs:count-specific {type}'; protected $description = 'Count the number of jobs of a specific type in the queue'; public function __construct() { parent::__construct(); } public function handle() { $type = $this->argument('type'); $redis = Redis::connection('horizon'); $keys = $redis->keys('*'); $count = 0; foreach ($keys as $key) { $jobData = $redis->hgetall($key); if (isset($jobData['data'])) { $jobPayload = json_decode($jobData['data'], true); if (isset($jobPayload['displayName']) && $jobPayload['displayName'] === $type) { $count++; } } } $this->info("Number of jobs of type {$type}: {$count}"); } }
Step 4: Run the Command
You can now run the command to count the jobs of a specific type:
php artisan jobs:count-specific 'App\Jobs\YourSpecificJob'
Explanation
- Fetching Job Keys: The command fetches all keys from Redis.
- Inspecting Job Data: For each key, it retrieves the job data and checks if the job type matches the specified type.
- Counting Jobs: It increments the count for each matching job type.
Troubleshooting
-
Redis Connection: Ensure that the Redis connection is correctly configured in your
config/database.php. -
Job Data Structure: The job data structure may vary, so adjust the key names (
data,displayName) as needed based on your job payload.
This approach should help you accurately measure the number of jobs of a specific type currently on the queue managed by Laravel Horizon.