Overview
Bull provides methods to retrieve jobs and count jobs by their status. These methods are useful for monitoring queue health, building dashboards, and managing job lifecycles.
GetterOpts Interface
interface GetterOpts {
excludeData: boolean; // Exclude the data field of the jobs
}
Retrieving Jobs
Queue.getJob()
Returns a job by its ID.
Signature
getJob(jobId: string): Promise<Job>
Parameters
The unique identifier of the job.
Returns
A promise that resolves to the Job instance, or null if the job cannot be found.
Example
const job = await queue.getJob('12345');
if (job) {
console.log(`Job ${job.id} status: ${await job.getState()}`);
} else {
console.log('Job not found');
}
This method does not return Repeatable Job configurations. Use getRepeatableJobs() for that.
Queue.getJobs()
Returns an array of jobs with specific statuses.
Signature
getJobs(types: JobStatus[], start?: number, end?: number, asc?: boolean): Promise<Job[]>
Parameters
Array of job statuses to retrieve. Valid values: 'completed', 'failed', 'delayed', 'active', 'waiting', 'paused'.
Starting index for range (0-based).
Ending index for range (-1 means all).
If true, return jobs in ascending order.
Returns
A promise that resolves to an array of Job instances.
Examples
// Get all completed jobs
const completed = await queue.getJobs(['completed']);
// Get first 10 failed jobs
const failed = await queue.getJobs(['failed'], 0, 9);
// Get all active and waiting jobs
const active = await queue.getJobs(['active', 'waiting']);
// Get jobs in ascending order
const oldest = await queue.getJobs(['completed'], 0, 4, true);
The start and end parameters are applied per job status. For example, getJobs(['completed', 'active'], 0, 4) returns the first 5 completed jobs AND the first 5 active jobs (up to 10 total).
This method does not return Repeatable Job configurations. Use getRepeatableJobs() for that.
Status-Specific Getters
These methods retrieve jobs in specific states with optional range and data exclusion.
Queue.getWaiting()
getWaiting(start?: number, end?: number, opts?: GetterOpts): Promise<Job[]>
Returns jobs waiting to be processed.
Example
const waiting = await queue.getWaiting(0, 9);
console.log(`${waiting.length} jobs waiting`);
Queue.getActive()
getActive(start?: number, end?: number, opts?: GetterOpts): Promise<Job[]>
Returns jobs currently being processed.
Example
const active = await queue.getActive();
for (const job of active) {
console.log(`Job ${job.id} is being processed`);
}
Queue.getDelayed()
getDelayed(start?: number, end?: number, opts?: GetterOpts): Promise<Job[]>
Returns jobs that are delayed (scheduled for future processing).
Example
const delayed = await queue.getDelayed();
for (const job of delayed) {
const delay = job.opts.delay;
console.log(`Job ${job.id} delayed by ${delay}ms`);
}
Queue.getCompleted()
getCompleted(start?: number, end?: number, opts?: GetterOpts): Promise<Job[]>
Returns successfully completed jobs.
Example
// Get last 100 completed jobs without their data
const completed = await queue.getCompleted(0, 99, { excludeData: true });
console.log(`Retrieved ${completed.length} completed jobs`);
Queue.getFailed()
getFailed(start?: number, end?: number, opts?: GetterOpts): Promise<Job[]>
Returns failed jobs.
Example
const failed = await queue.getFailed(0, 9);
for (const job of failed) {
console.log(`Job ${job.id} failed: ${job.failedReason}`);
}
Job Counters
Queue.count()
Returns the total number of jobs waiting or delayed.
Signature
Returns
Total number of jobs in waiting or delayed state.
Example
const totalJobs = await queue.count();
console.log(`${totalJobs} jobs pending`);
This value may only be accurate for a brief moment since other processes may be adding or processing jobs.
Queue.getJobCounts()
Returns job counts for all statuses.
Signature
getJobCounts(): Promise<JobCounts>
Returns
Object containing counts for each job status.interface JobCounts {
waiting: number;
active: number;
completed: number;
failed: number;
delayed: number;
}
Example
const counts = await queue.getJobCounts();
console.log('Queue status:');
console.log(` Waiting: ${counts.waiting}`);
console.log(` Active: ${counts.active}`);
console.log(` Completed: ${counts.completed}`);
console.log(` Failed: ${counts.failed}`);
console.log(` Delayed: ${counts.delayed}`);
Status-Specific Counters
Queue.getWaitingCount()
getWaitingCount(): Promise<number>
Returns the count of jobs waiting to be processed.
const waiting = await queue.getWaitingCount();
Queue.getActiveCount()
getActiveCount(): Promise<number>
Returns the count of jobs currently being processed.
const active = await queue.getActiveCount();
Queue.getDelayedCount()
getDelayedCount(): Promise<number>
Returns the count of delayed jobs.
const delayed = await queue.getDelayedCount();
Queue.getCompletedCount()
getCompletedCount(): Promise<number>
Returns the count of completed jobs.
const completed = await queue.getCompletedCount();
Queue.getFailedCount()
getFailedCount(): Promise<number>
Returns the count of failed jobs.
const failed = await queue.getFailedCount();
Queue.getPausedCount()
getPausedCount(): Promise<number>
DEPRECATED: Since only the queue can be paused, getWaitingCount() gives the same result.
Queue.getCountsPerPriority()
Returns job counts grouped by priority level.
Signature
getCountsPerPriority(priorities: number[]): Promise<{ [priority: number]: number }>
Parameters
Array of priority values to get counts for.
Returns
Object mapping priority values to job counts.
Example
// Get counts for specific priorities
const counts = await queue.getCountsPerPriority([1, 2, 3, 4, 5]);
console.log(counts);
// { 1: 10, 2: 25, 3: 50, 4: 15, 5: 5 }
// Calculate total high priority jobs (1-2)
const highPriority = counts[1] + counts[2];
console.log(`${highPriority} high priority jobs`);
Priority Distribution
async function getPriorityDistribution() {
const priorities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const counts = await queue.getCountsPerPriority(priorities);
const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
const distribution = {};
for (const [priority, count] of Object.entries(counts)) {
distribution[priority] = {
count,
percentage: ((count / total) * 100).toFixed(2) + '%'
};
}
return distribution;
}
This method only returns counts for jobs that have priority set. Jobs without priority are not included in the results.
Additional Getters
Queue.getWorkers()
Returns information about workers currently processing jobs.
Signature
getWorkers(): Promise<Array<Object>>
Returns
Array of worker objects with the same fields as Redis CLIENT LIST command.
Example
const workers = await queue.getWorkers();
console.log(`${workers.length} workers active`);
workers.forEach(worker => {
console.log(`Worker ${worker.id}: ${worker.addr}`);
});
Queue.getMetrics()
Returns metrics for completed or failed jobs.
Signature
getMetrics(type: 'completed' | 'failed', start = 0, end = -1): Promise<{
meta: {
count: number;
prevTS: number;
prevCount: number;
};
data: number[];
count: number;
}>
Parameters
type
'completed' | 'failed'
required
Type of metrics to retrieve.
Start index for data points.
End index for data points.
Example
const metrics = await queue.getMetrics('completed');
console.log(`Total completed: ${metrics.count}`);
console.log(`Data points: ${metrics.data.length}`);
Metrics must be enabled in the queue constructor options with metrics: { maxDataPoints: number }.
Common Patterns
Queue Dashboard
async function getQueueStatus() {
const counts = await queue.getJobCounts();
const workers = await queue.getWorkers();
const isPaused = await queue.isPaused();
return {
status: isPaused ? 'paused' : 'active',
workers: workers.length,
jobs: counts
};
}
app.get('/api/queue/status', async (req, res) => {
const status = await getQueueStatus();
res.json(status);
});
Failed Job Recovery
async function retryFailedJobs() {
const failed = await queue.getFailed();
console.log(`Retrying ${failed.length} failed jobs`);
for (const job of failed) {
await job.retry();
}
}
Job Monitoring
setInterval(async () => {
const counts = await queue.getJobCounts();
if (counts.failed > 100) {
console.warn('High number of failed jobs:', counts.failed);
// Send alert
}
if (counts.waiting > 1000) {
console.warn('Queue backlog:', counts.waiting);
// Scale up workers
}
}, 60000); // Check every minute
async function getCompletedJobsPage(page = 0, pageSize = 50) {
const start = page * pageSize;
const end = start + pageSize - 1;
const jobs = await queue.getCompleted(start, end, {
excludeData: true // Faster if you don't need job data
});
const total = await queue.getCompletedCount();
return {
jobs,
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize)
};
}