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
TheWorker class allows you to programmatically start and stop the scheduler:
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 youradonisrc.ts to load the scheduler provider in the appropriate environments.
Include specific environments
Specify which environments should load the scheduler:console- When running Ace commandsweb- When running the HTTP server
Enable for all environments
Alternatively, enable the scheduler provider globally:Worker API
TheWorker 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:
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:
async boot(): Promise<void>
Manually boots the worker (normally called automatically by start):
- 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.