Skip to main content
This guide will walk you through creating your first scheduled task, from defining a simple schedule to running it in production.

Create your first schedule

1

Define a scheduled callback

Open the start/scheduler.ts file and add a simple scheduled callback:
start/scheduler.ts
This schedule will execute the callback function every minute.
2

Run the scheduler

Start the scheduler using the Ace command:
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:
3

Create a scheduled command

For more complex tasks, create a dedicated Ace command. Generate a new command:
Implement the command logic:
commands/cleanup_old_logs.ts
4

Schedule the command

Add the command to your scheduler configuration:
start/scheduler.ts
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
Schedule it with arguments:
start/scheduler.ts

Common scheduling patterns

Here are some practical examples of scheduling tasks:

Advanced features

Prevent overlapping executions

If a task might take longer than its schedule interval, prevent overlapping executions:
start/scheduler.ts
You can also specify a lock expiration time (in milliseconds):
start/scheduler.ts

Using decorators

Define schedules directly on command classes using the @schedule decorator:
commands/purge_users.ts

Organizing with tags

Group related schedules using tags:
start/scheduler.ts

Lifecycle hooks

Execute code before and after scheduled tasks:
start/scheduler.ts

Timezone support

Run tasks in specific timezones:
start/scheduler.ts

Running in production

For production environments, use a process manager to keep the scheduler running:

Using PM2

ecosystem.config.json
Start the scheduler:

Using systemd

Create a systemd service file:
/etc/systemd/system/scheduler.service
Enable and start the service:

Using Docker

Add a scheduler service to your docker-compose.yml:
docker-compose.yml

Programmatic usage

For advanced use cases, you can manually control the scheduler worker:
When using programmatic initialization, ensure the scheduler provider is enabled for your environment in adonisrc.ts.

Listing schedules

View all registered schedules:
This command displays all scheduled tasks with their frequencies and configurations.

Next steps

Now that you’ve created your first scheduled tasks, explore more advanced features: