### Create Test Job (node ace) Source: https://adonis-jobs.nemo.engineering/guides/installation Generates a sample job file named 'test_job.ts' in the 'app/jobs' directory. This is used to verify that the package installation and configuration are successful. ```bash node ace make:job test ``` -------------------------------- ### Install BullMQ or BullMQ Pro (npm) Source: https://adonis-jobs.nemo.engineering/guides/installation Installs either the open-source BullMQ or the enterprise BullMQ Pro package using npm. Choose the appropriate command based on your BullMQ version requirement. ```bash # For BullMQ (open-source version) npm install bullmq # For BullMQ Pro (enterprise version) npm install @taskforcesh/bullmq-pro ``` -------------------------------- ### Create Jobs Directory (mkdir) Source: https://adonis-jobs.nemo.engineering/guides/installation Creates the 'app/jobs' directory in your project. This directory will be used to store your job files and needs to be configured in `adonisrc.ts`. ```bash mkdir app/jobs ``` -------------------------------- ### Install Adonis Jobs Package (node ace) Source: https://adonis-jobs.nemo.engineering/guides/installation Adds the @nemoventures/adonis-jobs package to your AdonisJS application. This command also sets up the queue configuration file and updates necessary application configurations. ```bash node ace add @nemoventures/adonis-jobs ``` -------------------------------- ### Start Job Queue Workers with `queue:work` Source: https://adonis-jobs.nemo.engineering/reference Initiates workers to process jobs from the defined queues. This command supports starting workers for all queues, specific queues, listing available queues, forcing an exit, and utilizing the app router. ```bash # Start workers for all queues node ace queue:work # Start workers for specific queues node ace queue:work --queues=emails,notifications # List available queues node ace queue:work --list # Force exit without waiting for active jobs node ace queue:work --force-exit # Use app router instead of dedicated server node ace queue:work --use-app-router ``` -------------------------------- ### Configure Job Directory Path (adonisrc.ts) Source: https://adonis-jobs.nemo.engineering/guides/installation Configures the 'app/jobs' directory path within your AdonisJS application's configuration file (`adonisrc.ts`). This allows AdonisJS to locate your job files. ```typescript import { defineConfig } from '@adonisjs/core/hash' export default defineConfig({ // ... existing code ... directories: { jobs: 'app/jobs', }, // ... existing code ... }) ``` -------------------------------- ### Setup Queue Dashboard Routes in AdonisJS Source: https://adonis-jobs.nemo.engineering/guides/queue-dashboard Adds the QueueDash dashboard routes to your AdonisJS application by importing and prefixing the routes in `start/routes.ts`. This makes the dashboard accessible at `/admin/queue`. ```typescript import router from '@adonisjs/core/services/router' import { queueDashUiRoutes } from '@nemoventures/adonis-jobs/ui/queuedash' // Add queue dashboard routes router.group(() => { queueDashUiRoutes().prefix('/queue') }).prefix('/admin') ``` -------------------------------- ### Enable BullMQ Pro Features in Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/configuration Activates BullMQ Pro features by declaring the version in the type definitions. Requires `@taskforcesh/bullmq-pro` to be installed. ```typescript declare module '@nemoventures/adonis-jobs/types' { interface Queues extends InferQueues {} interface BullVersion { version: 'pro' // Enable BullMQ Pro features } } ``` -------------------------------- ### Start AdonisJS Queue Workers Source: https://adonis-jobs.nemo.engineering/guides/queue-management Starts worker processes to handle jobs from the AdonisJS queue. Workers can be started for all queues or specific named queues. Multiple workers can be run concurrently or on different machines for scaling. ```bash node ace queue:work node ace queue:work --queue emails node ace queue:work --queue emails,reports,background ``` -------------------------------- ### Configure Prometheus Collector for Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/observability Integrates the BullMQ job metrics collector with the `@julr/adonisjs-prometheus` package. Ensure `@julr/adonisjs-prometheus` is installed and configured. This code adds the `bullmqCollector` to your Prometheus configuration. ```typescript import { defineConfig } from '@julr/adonisjs-prometheus' import { bullmqCollector } from '@nemoventures/adonis-jobs/metrics' import env from '#start/env' export default defineConfig({ // ... collectors: [ // ... other collectors bullmqCollector(), ], }) ``` -------------------------------- ### Overriding Default Job Options When Dispatching Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This example shows how to dispatch a job with default options set and how to override specific options when dispatching. The `.with()` method allows for granular control over options like 'attempts' and 'delay', merging with and overriding the default configurations. ```typescript // These options will be automatically applied await SendEmailJob.dispatch(data) // You can still override specific options if needed when dispatching await SendEmailJob.dispatch(data) .with('attempts', 3) .with('delay', 5000) ``` -------------------------------- ### Configure Connection Per Queue in Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/configuration Allows specifying a distinct Redis connection for each queue. This example assigns the 'main' connection to the 'default' queue and the 'emails' connection to the 'emails' queue. ```typescript const queueConfig = defineConfig({ queues: { default: { connection: { connectionName: 'main' }, // Use 'main' connection for default queue }, emails: { connection: { connectionName: 'emails' }, // Use 'emails' connection for emails queue }, }, }) ``` -------------------------------- ### Dependency Injection in AdonisJS Jobs Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This example demonstrates how to use dependency injection within job classes and methods in AdonisJS. It shows injecting services like `MailService` via the constructor and other services within the `process` method using the `@inject()` decorator. ```typescript import { inject } from '@adonisjs/core' import { Job } from '@nemoventures/adonis-jobs' import MailService from '#services/mail_service' export type SendEmailJobData = { to: string subject: string body: string } @inject() export default class SendEmailJob extends Job { constructor(private mailService: MailService) { super() } @inject() async process(anotherService: AnotherService): Promise { await this.mailService.send(this.data) await anotherService.doSomething(this.data) } } ``` -------------------------------- ### Protect Queue Dashboard Routes with Authentication Middleware Source: https://adonis-jobs.nemo.engineering/guides/queue-dashboard Secures the Queue Dashboard routes using AdonisJS authentication middleware. This example uses the 'basicAuth' guard, but can be customized for other guards. ```typescript import { middleware } from '#start/kernel' router.group(() => { queueDashUiRoutes().prefix('/queue') }) .prefix('/admin') .use(middleware.auth({ guards: ['basicAuth'] })) ``` -------------------------------- ### Handling Job Failures with onFailed Method in TypeScript Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This TypeScript example shows how to override the `onFailed` method to implement custom logic when a job fails. It logs the error, checks if all attempts have been made using `this.allAttemptsMade()`, and optionally notifies administrators. ```typescript export default class SendEmailJob extends Job { async process(): Promise { // Email sending logic that might fail } async onFailed(): Promise { this.logger.error({ err: this.error }, 'Email job failed') // Check if all attempts have been exhausted if (this.allAttemptsMade()) { await this.notifyAdministrators() } } } ``` -------------------------------- ### Set Default Queue for Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/configuration Specifies the default queue to use when no queue is explicitly defined for jobs. This example sets 'notifications' as the default queue and defines 'notifications' and 'processing' as available queues. ```typescript const queueConfig = defineConfig({ defaultQueue: 'notifications', // Jobs go to 'notifications' queue by default queues: { notifications: {}, processing: {}, }, }) ``` -------------------------------- ### Configure Shield CSRF Protection for Queue Dashboard Source: https://adonis-jobs.nemo.engineering/guides/queue-dashboard Excludes the Queue Dashboard routes from CSRF protection in the Shield configuration. This allows job deletion and re-running directly from the dashboard by checking if the request URL starts with `/admin/queue`. ```typescript csrf: { enabled: true, exceptRoutes: (ctx) => { return ctx.request.url().startsWith('/admin/queue') }, } ``` -------------------------------- ### Log from Services used by Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/observability Illustrates how to set up dependency injection in a job class to use a service that also logs. When `multiLogger` is enabled and the service is injected from a job context, its logs will also be sent to BullMQ. If the service is used outside a job, logs go only to Pino. ```typescript import { inject } from '@adonisjs/core' import { Job } from '@nemoventures/adonis-jobs' import { EmailService } from '#services/test_service' @inject() export default class MyJob extends Job { constructor(protected testService: EmailService) { super() } async handle(): Promise { // This will be logged to both Pino and BullMQ this.logger.info('Starting file write job') // The service can also use logging that will be properly routed await this.email.processData(this.data.data) } } ``` -------------------------------- ### Generate a New Job with Ace Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This command generates a new job file using the Ace CLI. It creates a boilerplate file for a job, typically named with a '_job.ts' suffix, in the 'app/jobs' directory. ```bash node ace make:job send_email ``` -------------------------------- ### Configure Job Options Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Customize job processing behavior using the `.with()` method, such as setting retry attempts and backoff strategies. These options are derived from BullMQ. ```typescript await SendEmailJob .dispatch(emailData) .with('attempts', 5) .with('backoff', { type: 'exponential', delay: 2000, }) .with('delay', 1000) ``` -------------------------------- ### Service Logging with Automatic MultiLogger Injection Source: https://adonis-jobs.nemo.engineering/guides/observability Demonstrates a service class designed to work with Adonis Jobs' `multiLogger`. The `Logger` is automatically injected by AdonisJS. When injected from a job context with `multiLogger` enabled, logs from this service will go to both Pino and BullMQ. Otherwise, they log only to Pino. ```typescript import { inject } from '@adonisjs/core' import { Logger } from '@adonisjs/core/logger' @inject() export class TestService { /** * Here, the MultiLogger will be automatically injected when * injected from a Job. * * If the service is also used outside of a Job context, * no worries, the logger will still be available * and will log to Pino targets only. */ constructor(protected logger: Logger) {} async processData(data: string): Promise { // This log will be sent to both Pino and BullMQ when multiLogger is enabled this.logger.info('Processing data in service', { dataLength: data.length }) // Your service logic here } } ``` -------------------------------- ### Setting Default BullMQ Options for a Job in TypeScript Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This code defines default BullMQ options for a job class using the static `options` property. These options, such as `attempts`, `backoff`, `removeOnComplete`, and `removeOnFail`, are automatically applied when the job is dispatched unless overridden. ```typescript import { Job } from '@nemoventures/adonis-jobs' import type { BullJobsOptions } from '@nemoventures/adonis-jobs/types' export default class SendEmailJob extends Job { static options: BullJobsOptions = { attempts: 5, backoff: { type: 'exponential', delay: 1000, }, removeOnComplete: 10, removeOnFail: 50, } async process(): Promise { // Job logic } } ``` -------------------------------- ### Accessing Job Properties in TypeScript Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This code snippet illustrates how to access various properties available within a job's `process` method. It shows how to retrieve job data (`this.data`), the BullMQ Job instance (`this.job`), the BullMQ Worker instance (`this.worker`), and the logger instance (`this.logger`). ```typescript export default class SendEmailJob extends Job { async process(): Promise { // Job data passed during dispatch const emailData = this.data // BullMQ Job instance const jobId = this.job // BullMQ Worker instance const worker = this.worker // Logger instance this.logger.info('Processing email job', { to: emailData.to }) return { messageId: 'abc123', success: true } } } ``` -------------------------------- ### List All Scheduled Jobs with `queue:scheduler:list` Source: https://adonis-jobs.nemo.engineering/reference Displays a list of all scheduled jobs within the AdonisJS application. This command can be filtered by a specific queue name. ```bash # List all scheduled jobs node ace queue:scheduler:list # Filter by queue node ace queue:scheduler:list --queue=emails ``` -------------------------------- ### Create New Job Class with `make:job` Source: https://adonis-jobs.nemo.engineering/reference Generates a new job class file using the `make:job` command. This command requires the name of the job class as an argument. It helps in structuring and creating new job definitions within the AdonisJS application. ```bash node ace make:job SendEmail ``` -------------------------------- ### Customize Prometheus Histogram Buckets for Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/observability Allows customization of histogram buckets for job processing time and completion time metrics when using the `bullmqCollector`. This provides finer control over metric aggregation. ```typescript bullmqCollector({ processingTimeBuckets: [50, 100, 250, 500, 1000, 5000], completionTimeBuckets: [100, 500, 1000, 5000, 10000, 60000] }) ``` -------------------------------- ### Log within Adonis Job with Trace ID Source: https://adonis-jobs.nemo.engineering/guides/observability Demonstrates how to access and use the child logger instance provided within Adonis Job classes. This logger automatically includes the trace ID for context. Logs are initially sent to Pino targets. ```typescript import { Job } from '@nemoventures/adonis-jobs' export default class MyJob extends Job { async handle() { // Use this.logger to log messages with trace context this.logger.info('Processing job', { jobId: this.id }) // Your job logic here } } ``` -------------------------------- ### Schedule a Job Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Schedule jobs to run at specific intervals or times using the `JobScheduler`. This utilizes BullMQ's job scheduling capabilities for recurring tasks. ```typescript await JobScheduler.schedule({ // A key to identify the job. Will be used to prevent duplicate jobs. // And can be used to remove/update the job later. key: 'file-writer-scheduler', job: WriteFileJob, data: { data: 'Scheduled via JobScheduler!' }, // Repeat options. Check BullMQ's documentation for available strategies. repeat: { pattern: '*/15 * * * * *' }, // Queue to dispatch the job to queue: params.queue, // Additional job options options: { attempts: 3, backoff: { type: 'exponential', delay: 2000, }, }, }) ``` -------------------------------- ### Enable MultiLogger in Adonis Jobs Configuration Source: https://adonis-jobs.nemo.engineering/guides/observability Shows how to enable the `multiLogger` option in the Adonis Jobs configuration file (`config/queue.ts`). When enabled, logs generated by `this.logger` within jobs will also be sent to the BullMQ logger. ```typescript const queueConfig = defineConfig({ // ... multiLogger: { enabled: true, }, }) ``` -------------------------------- ### Dispatch a Job (Basic) Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Dispatch a job to a queue for asynchronous processing. This is the most straightforward way to send a job without immediately needing its result. ```typescript import SendEmailJob from '#jobs/send_email_job' // Dispatch and forget await SendEmailJob.dispatch({ to: 'user@example.com', subject: 'Welcome!', template: 'welcome', variables: { name: 'John' } }) ``` -------------------------------- ### Dispatch Jobs in a Chain Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Execute a series of jobs sequentially using `JobChain`, where each job depends on the completion of the previous one. If any job fails, the chain stops. ```typescript import { JobChain } from '@nemoventures/adonis-jobs' await new JobChain([ ProcessOrderJob.dispatch({ orderId: '123' }), SendConfirmationEmailJob.dispatch({ orderId: '123' }), UpdateInventoryJob.dispatch({ orderId: '123' }), ]).dispatch() ``` -------------------------------- ### AdonisJS Job File Naming Conventions Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This snippet illustrates the correct and incorrect file naming conventions for AdonisJS job files. Jobs must end with the `_job.ts` suffix and export a default class extending `Job` to be automatically discovered. ```typescript ✅ app/jobs/send_email_job.ts ✅ app/jobs/process_payment_job.ts ✅ app/jobs/generate_report_job.ts ❌ app/jobs/send_email.ts ❌ app/jobs/email_sender.ts ``` -------------------------------- ### Dispatch Job to Specific Queue Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Send a job to a particular queue using the `.onQueue()` method. This allows for targeted processing of different job types. ```typescript await SendEmailJob .dispatch(emailData) .onQueue('emails') ``` -------------------------------- ### Enable Worker-Specific Prometheus Metrics Endpoint Source: https://adonis-jobs.nemo.engineering/guides/observability Enables the `metrics` configuration for the AdonisJS jobs package, allowing each worker to expose its own Prometheus metrics endpoint. This is useful for monitoring individual worker health and performance. ```typescript const queueConfig = defineConfig({ // ... metrics: { enabled: true, endpoint: '/internal/metrics', }, }) ``` -------------------------------- ### Configure OpenTelemetry Default Job Attributes Source: https://adonis-jobs.nemo.engineering/guides/observability Configures the OpenTelemetry integration for AdonisJS jobs by defining default attributes to be added to spans for each processed job. This enhances tracing by including job-specific information. ```typescript const queueConfig = defineConfig({ // ... otel: { defaultJobAttributes: (jobInstance) => ({ ['apm.root_name']: jobInstance.job.name, }), }, }) ``` -------------------------------- ### Define Job Data Types and Process Logic in TypeScript Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This TypeScript code defines the expected data structure for a job and its return type. The `process` method contains the core logic to be executed in the background, including sending an email based on the provided data. ```typescript import { Job } from '@nemoventures/adonis-jobs' /** * Here you can define the data type your job expects. */ export type SendEmailJobData = { to: string subject: string template: string variables: Record } /** * Then you can also define the return type of your job. */ export type SendEmailJobReturn = { messageId: string success: boolean } export default class SendEmailJob extends Job { async process(): Promise { const { to, subject, template, variables } = this.data // Send email logic here const messageId = await sendEmail({ to, subject, template, variables }) return { messageId, success: true } } } ``` -------------------------------- ### Create Job Flows with Parent-Child Relationships Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Orchestrate complex workflows with parent-child job dependencies using `JobFlow`. This allows for intricate job execution patterns and nested workflows. ```typescript import { JobFlow } from '@nemoventures/adonis-jobs' const parentJob = ProcessOrderJob.dispatch({ orderId: '123' }) const flow = new JobFlow(parentJob) // Add child jobs that run after parent completes flow.addChildJob(SendEmailJob.dispatch({ orderId: '123' })) flow.addChildJob(UpdateInventoryJob.dispatch({ orderId: '123' })) // Add nested children flow.addChildJob( GenerateInvoiceJob.dispatch({ orderId: '123' }), (childFlow) => { childFlow.addChildJob(EmailInvoiceJob.dispatch({ orderId: '123' })) } ) await flow.dispatch() ``` -------------------------------- ### Clean Jobs Older Than a Grace Period with `queue:clean` Source: https://adonis-jobs.nemo.engineering/reference Cleans jobs of a specific type that are older than a defined grace period. Supports cleaning completed, failed jobs, and allows specifying the queue, grace period in milliseconds, and a limit for the number of jobs to clean. ```bash # Clean completed jobs (default) node ace queue:clean # Clean specific job type node ace queue:clean --type=failed # Clean with grace period (5 minutes) node ace queue:clean --grace=300000 # Clean specific queue with limit node ace queue:clean --queue=emails --limit=50 --type=completed # Force in production node ace queue:clean --force ``` -------------------------------- ### Configure Queue Settings in Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/configuration Defines specific settings for individual queues, such as 'emails'. This includes default job options (like removal on completion/failure, retry attempts, backoff strategy) and default worker options (concurrency, removal age). ```typescript const queueConfig = defineConfig({ queues: { emails: { // Default options for jobs added to this queue defaultJobOptions: { removeOnComplete: 10, // Keep 10 completed jobs removeOnFail: 50, // Keep 50 failed jobs attempts: 3, // Retry failed jobs 3 times backoff: { type: 'exponential', delay: 2000, }, }, // Default options for workers processing this queue defaultWorkerOptions: { concurrency: 5, // Process 5 jobs simultaneously per worker removeOnComplete: { age: 24 * 3600 }, // Remove completed jobs after 24h removeOnFail: { age: 7 * 24 * 3600 }, // Remove failed jobs after 7 days }, }, }, }) ``` -------------------------------- ### Bulk Dispatch Jobs Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Dispatch multiple jobs concurrently using the `BulkDispatcher`. This is efficient for performing the same action on a collection of items. ```typescript // Send welcome emails to multiple new users const newUsers = await User .query() .where('welcome_email_sent', false) await new BulkDispatcher( newUsers.map(user => SendWelcomeEmailJob.dispatch({ userId: user.id, email: user.email, name: user.fullName }) ) ).dispatch() ``` -------------------------------- ### Configure Health Checks for Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/configuration Sets up an HTTP server for health checks within the `node ace queue:work` command. This enables monitoring of queue status and worker health, using checks like Redis connection and memory usage. ```typescript const queueConfig = defineConfig({ /** * Health check configuration for monitoring queue infrastructure */ healthCheck: { enabled: true, endpoint: '/internal/healthz', checks: ({ connection }) => [ new RedisCheck(connection), new RedisMemoryUsageCheck(connection) .warnWhenExceeds('100MB') .failWhenExceeds('200MB'), ], }, }) ``` -------------------------------- ### Explicitly Failing a Job in TypeScript Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This TypeScript code demonstrates how to explicitly fail a job using `this.fail()`. Calling this method with a reason prevents the job from retrying and moves it directly to the failed state, indicating an unrecoverable error. ```typescript export default class ProcessPaymentJob extends Job { async process(): Promise { if (!this.data.paymentMethodId) { this.fail('Payment method ID is required') return } // Process payment } } ``` -------------------------------- ### Setting a Default Queue for a Job in TypeScript Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs This TypeScript code defines a static property `defaultQueue` on the job class to specify which queue it should use by default. This avoids the need to specify the queue name every time the job is dispatched. ```typescript import { Queues } from '@nemoventures/adonis-jobs/types' export default class SendEmailJob extends Job { static defaultQueue: keyof Queues = 'emails' async process(): Promise { // Job logic } } ``` -------------------------------- ### Enable Shared Redis Connection in Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/configuration Sets the 'useSharedConnection' option to true, enabling all queues to utilize a single Redis connection. This is recommended for reducing resource usage and improving performance. ```typescript const queueConfig = defineConfig({ useSharedConnection: true, // Use a single shared Redis connection }) ``` -------------------------------- ### Handling Renamed Job Classes with nameOverride in AdonisJS Source: https://adonis-jobs.nemo.engineering/guides/creating-jobs Demonstrates how to use the `nameOverride` static property within an AdonisJS job class to ensure compatibility with previously dispatched jobs after renaming the class. This prevents processing failures when the class name changes but the original dispatched jobs still reference the old name. ```typescript import { Job } from '@ioc:Adonis/Queue' interface SendEmailJobData {} export default class SendEmailNotificationJob extends Job { // This will allow the previously dispatched jobs to be processed correctly static nameOverride = 'SendEmailJob' async process(): Promise { // Job logic } } ``` -------------------------------- ### Dispatch a Job and Wait for Result Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Dispatch a job and wait for its execution to complete, returning the result. Useful when the outcome of a job is immediately required for subsequent operations. ```typescript const result = await SendEmailJob .dispatch({ to: 'user@example.com', subject: 'Test' }) .waitResult() console.log('Email sent with ID:', result.messageId) ``` -------------------------------- ### Specify Redis Connection for Adonis Jobs Source: https://adonis-jobs.nemo.engineering/guides/configuration Configures the Redis connection to be used for dispatching and processing jobs. The 'redisConnection' property must match a connection name defined in your `config/redis.ts` file. ```typescript const queueConfig = defineConfig({ redisConnection: 'main', // Use 'main' connection from config/redis.ts queues: { default: {}, }, }) ``` -------------------------------- ### Clean AdonisJS Queues Source: https://adonis-jobs.nemo.engineering/guides/queue-management Removes jobs from AdonisJS queues based on their state and an optional grace period. Jobs in 'completed' or 'failed' states can be cleaned, with options to specify a grace period in seconds or a limit for failed jobs. Specific queues can also be targeted. ```bash # Clean completed jobs older than 1 hour node ace queue:clean --type completed --grace 3600 # Clean failed jobs with limit node ace queue:clean --type failed --limit 100 # Clean specific queue node ace queue:clean --queue emails --type completed ``` -------------------------------- ### Clear All or Specific Jobs from Queues with `queue:clear` Source: https://adonis-jobs.nemo.engineering/reference Removes all jobs from specified queues or all queues. This command allows clearing individual queues or all of them, with an option to force the operation in production environments. ```bash # Clear all queues node ace queue:clear # Clear specific queue node ace queue:clear --queue=emails # Force in production node ace queue:clear --force ``` -------------------------------- ### Clear AdonisJS Queues Source: https://adonis-jobs.nemo.engineering/guides/queue-management Completely removes all jobs from an AdonisJS queue. This command can be used to clear the default queue or a specific queue. A `--force` option is available to bypass the confirmation prompt. ```bash # Clear all jobs from default queue node ace queue:clear # Clear specific queue node ace queue:clear --queue background-tasks # Clear without confirmation node ace queue:clear --queue critical --force ``` -------------------------------- ### Clear All Scheduled Jobs with `queue:scheduler:clear` Source: https://adonis-jobs.nemo.engineering/reference Removes all scheduled jobs from the queue system. It can target specific queues and has an option to skip the confirmation prompt for production use. ```bash # Clear all scheduled jobs node ace queue:scheduler:clear # Clear from specific queue node ace queue:scheduler:clear --queue=emails # Skip confirmation node ace queue:scheduler:clear --force ``` -------------------------------- ### Set Default Queue in Job Class Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Define a default queue for a job class by setting the `defaultQueue` static property. All dispatches from this class will use this queue unless overridden. ```typescript export default class SendEmailJob extends Job { static defaultQueue: keyof Queues = 'emails' async process(): Promise { // Job logic } } // This will automatically use the 'emails' queue await SendEmailJob.dispatch(emailData) ``` -------------------------------- ### Drain Waiting and Active Jobs from Queues with `queue:drain` Source: https://adonis-jobs.nemo.engineering/reference Removes all waiting and active jobs from queues. Similar to `queue:clear`, this command can target specific queues or all of them and includes a force option for production. ```bash # Drain all queues node ace queue:drain # Drain specific queue node ace queue:drain --queue=emails # Force in production node ace queue:drain --force ``` -------------------------------- ### Remove a Specific Scheduled Job with `queue:scheduler:remove` Source: https://adonis-jobs.nemo.engineering/reference Deletes a particular scheduled job identified by its unique key. This command is used for granular control over scheduled jobs. ```bash node ace queue:scheduler:remove "my-scheduled-job-key" ``` -------------------------------- ### Drain AdonisJS Queues Source: https://adonis-jobs.nemo.engineering/guides/queue-management Removes all jobs from an AdonisJS queue that are in a 'waiting' or 'delayed' state. Jobs that are currently active, completed, or failed are not affected. This command can target the default queue or a specific queue. ```bash # Drain default queue node ace queue:drain # Drain specific queue node ace queue:drain --queue notifications ``` -------------------------------- ### Remove a Scheduled Job Source: https://adonis-jobs.nemo.engineering/guides/dispatching-jobs Remove a previously scheduled job using its unique key with the `JobScheduler.remove()` method. This stops future executions of the job. ```typescript await JobScheduler.remove('file-writer-scheduler') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.