Advanced configuration options for AdonisJS Scheduler
This guide covers advanced configuration patterns for AdonisJS Scheduler, including provider setup, environment-based configuration, and custom worker configuration.
The scheduler is registered as a provider in your AdonisJS application. During installation, the provider is automatically configured in your adonisrc.ts file.
Configure global hooks that run for all scheduled tasks:
start/scheduler.ts
import scheduler from 'adonisjs-scheduler/services/main'import logger from '@adonisjs/core/services/logger'// Hook that runs before scheduler bootsscheduler.onBoot(async () => { logger.info('Scheduler is booting...') // Initialize connections, load resources, etc.})// Hook that runs before each task execution startsscheduler.onStarting(async ({ tag }) => { logger.info(`Starting tasks with tag: ${tag}`)})// Hook that runs after scheduler is fully startedscheduler.onStarted(async ({ tag }) => { logger.info(`Scheduler started successfully for tag: ${tag}`)})
import scheduler from 'adonisjs-scheduler/services/main'import env from '#start/env'const appTimezone = env.get('APP_TIMEZONE', 'UTC')scheduler .call(() => { // This task runs in the application's timezone }) .daily() .timezone(appTimezone)
For advanced use cases, you can manually instantiate and configure the worker:
start/scheduler_worker.ts
import { Worker } from 'adonisjs-scheduler'import app from '@adonisjs/core/services/app'import logger from '@adonisjs/core/services/logger'const worker = new Worker(app)// Boot the workerawait worker.boot()// Start with specific tagawait worker.start('production')// Later, stop the worker gracefullyprocess.on('SIGTERM', async () => { logger.info('Stopping scheduler worker...') await worker.stop() process.exit(0)})
Run multiple scheduler workers with different tags:
import { Worker } from 'adonisjs-scheduler'import app from '@adonisjs/core/services/app'// Worker for critical tasksconst criticalWorker = new Worker(app)await criticalWorker.start('critical')// Worker for background tasksconst backgroundWorker = new Worker(app)await backgroundWorker.start('background')
When running multiple workers, ensure each worker handles a unique set of tags to avoid duplicate task execution.
Configure scheduler behavior using environment variables:
.env
# Application timezone (affects all schedules by default)APP_TIMEZONE=America/New_York# Custom environment flagSCHEDULER_ENABLED=true# Tag to run (useful for multi-server setups)SCHEDULER_TAG=production
Use them in your configuration:
start/scheduler.ts
import scheduler from 'adonisjs-scheduler/services/main'import env from '#start/env'// Only register schedules if enabledif (env.get('SCHEDULER_ENABLED') === 'true') { scheduler .call(() => { // Task }) .everyMinute() .timezone(env.get('APP_TIMEZONE', 'UTC'))}