Open the start/scheduler.ts file and add a simple scheduled callback:
start/scheduler.ts
import scheduler from 'adonisjs-scheduler/services/main'scheduler.call(() => { console.log('Task running at:', new Date().toISOString())}).everyMinute()
This schedule will execute the callback function every minute.
2
Run the scheduler
Start the scheduler using the Ace command:
node ace scheduler:run
You should see the message printed to the console every minute.
During development, use the --watch flag to automatically restart the scheduler when files change:
node ace scheduler:run --watch
3
Create a scheduled command
For more complex tasks, create a dedicated Ace command. Generate a new command:
node ace make:command cleanup_old_logs
Implement the command logic:
commands/cleanup_old_logs.ts
import { BaseCommand } from '@adonisjs/core/ace'import { CommandOptions } from '@adonisjs/core/types/ace'export default class CleanupOldLogs extends BaseCommand { static commandName = 'cleanup:old:logs' static description = 'Clean up log files older than 30 days' static options: CommandOptions = { startApp: true, } async run() { this.logger.info('Cleaning up old logs...') // Your cleanup logic here // Example: Delete logs older than 30 days this.logger.success('Cleanup completed!') }}
4
Schedule the command
Add the command to your scheduler configuration:
start/scheduler.ts
import scheduler from 'adonisjs-scheduler/services/main'import CleanupOldLogs from '#commands/cleanup_old_logs'scheduler.command(CleanupOldLogs).daily()
The command will now run every day at midnight.
5
Schedule with arguments
If your command accepts arguments, pass them when scheduling:
commands/purge_users.ts
import { BaseCommand, args } from '@adonisjs/core/ace'import { CommandOptions } from '@adonisjs/core/types/ace'export default class PurgeUsers extends BaseCommand { static commandName = 'purge:users' static description = 'Purge inactive users' static options: CommandOptions = { startApp: true, } @args.string() declare olderThan: string async run() { this.logger.info(`Purging users older than ${this.olderThan}`) // Your purge logic here }}
Schedule it with arguments:
start/scheduler.ts
import scheduler from 'adonisjs-scheduler/services/main'import PurgeUsers from '#commands/purge_users'scheduler.command(PurgeUsers, ['30 days']).weekly()
scheduler.withTag(() => { scheduler.command('send:notifications').everyMinute() scheduler.command('process:queue').everyFiveMinutes()}, 'background-jobs')// Run only specific tags// node ace scheduler:run --tag background-jobs