Skip to main content
Besides using the scheduler:run command, you can manually initialize and control the scheduler worker in your code. This approach is useful when you need fine-grained control over the scheduler lifecycle or want to embed the scheduler in a custom application.

Using the Worker class

The Worker class allows you to programmatically start and stop the scheduler:
This gives you direct control over when the scheduler starts and stops, without relying on the CLI command.

When to use this approach

Consider using the manual worker approach when:

Embedding in a web server

You want to run the scheduler alongside your HTTP server in the same process:

Custom initialization logic

You need to perform custom setup before starting the scheduler:

Running multiple workers

You want to run multiple scheduler workers with different tags in the same process:

Testing

You need to control the scheduler lifecycle during testing:

Configuration for manual worker

When using the manual worker approach, you need to configure your adonisrc.ts to load the scheduler provider in the appropriate environments.

Include specific environments

Specify which environments should load the scheduler:
This configuration loads the scheduler in both:
  • console - When running Ace commands
  • web - When running the HTTP server

Enable for all environments

Alternatively, enable the scheduler provider globally:
If you don’t configure the scheduler provider for your target environment, the worker will not be able to load scheduled tasks.

Worker API

The Worker class provides the following methods:

constructor(app: ApplicationService)

Creates a new worker instance:

async start(tag?: string): Promise<void>

Starts the scheduler worker with an optional tag filter:
The start method:
  • Boots the scheduler and loads all schedules
  • Registers cron tasks based on the tag filter
  • Begins executing scheduled tasks

async stop(): Promise<void>

Stops all running scheduled tasks:
This gracefully stops all cron tasks but does not wait for currently executing tasks to complete.

async boot(): Promise<void>

Manually boots the worker (normally called automatically by start):
The boot process:
  • Loads the scheduler from the container
  • Calls the scheduler’s boot method
  • Loads command modules

Complete example

Here’s a complete example of a custom server that runs both the HTTP server and scheduler:

Worker state management

The worker maintains internal state to prevent duplicate initialization:

Error handling

When using the manual worker, implement proper error handling:
The worker logs errors internally using the application’s logger. Individual task failures do not stop the worker.