Getting Started with Tasks
The tasks plugin provides a powerful way to schedule and manage background tasks in your CommandKit bot. Whether you need to run periodic maintenance, send scheduled reminders, or perform data cleanup, the tasks plugin has you covered.
Installation
First, install the tasks plugin:
npm install @commandkit/tasks
Basic Setup
Add the tasks plugin to your CommandKit configuration:
import { defineConfig } from 'commandkit/config';
import { tasks } from '@commandkit/tasks';
export default defineConfig({
plugins: [tasks()],
});
Setting Up a Driver (optional)
By default, the plugin will initialize the sqlite driver. You can set up a different driver by calling setDriver
function from the @commandkit/tasks
package.
If you want to disable the default driver initialization behavior, you can pass initializeDefaultDriver: false
to the tasks()
options in your commandkit config.
import { setDriver } from '@commandkit/tasks';
import { SQLiteDriver } from '@commandkit/tasks/sqlite';
// For development
setDriver(new SQLiteDriver('./tasks.db'));
// For production, use BullMQ with Redis
// setDriver(new BullMQDriver({ host: 'localhost', port: 6379 }));
Creating Your First Task
Create a file in src/app/tasks/
to define your tasks:
import { task } from '@commandkit/tasks';
export default task({
name: 'daily-backup',
schedule: '0 0 * * *', // Daily at midnight (cron string)
async execute(ctx) {
// Your task logic here
await performBackup();
console.log('Daily backup completed!');
},
});
Task Structure
Every task has the following components:
- name: A unique identifier for the task
- schedule: When the task should run (optional for manual execution)
- execute: The main function that performs the task work
- prepare: Optional function to determine if the task should run
Schedule Types
Cron Schedules
Use cron expressions for recurring tasks:
export default task({
name: 'hourly-task',
schedule: '0 * * * *', // Every hour
async execute(ctx) {
// Task logic
},
});
Date Schedules
Schedule tasks for specific times:
export default task({
name: 'reminder',
schedule: new Date('2024-01-01T12:00:00Z'), // Specific date
async execute(ctx) {
// Send reminder
},
});
// Or use timestamps
export default task({
name: 'timestamp-task',
schedule: Date.now() + 60000, // 1 minute from now
async execute(ctx) {
// Task logic
},
});
Task Context
The execute
function receives a context object with useful properties:
export default task({
name: 'context-example',
schedule: '0 */6 * * *', // Every 6 hours
async execute(ctx) {
// Access the Discord.js client
const client = ctx.commandkit.client;
// Access custom data (for dynamic tasks)
const { userId, message } = ctx.data;
// Use the temporary store
ctx.store.set('lastRun', Date.now());
// Send a message to a channel
const channel = client.channels.cache.get('channel-id');
if (channel?.isTextBased()) {
await channel.send('Task executed!');
}
},
});
Conditional Execution
Use the prepare
function to conditionally execute tasks:
export default task({
name: 'conditional-task',
schedule: '0 */2 * * *', // Every 2 hours
async prepare(ctx) {
// Only run if maintenance mode is not enabled
return !ctx.commandkit.store.get('maintenance-mode');
},
async execute(ctx) {
await performMaintenanceChecks();
},
});
Next Steps
Now that you have the basics, explore:
- Task Drivers - Learn about different persistence options
- Dynamic Tasks - Create tasks on-demand from commands
- Advanced Patterns - Best practices and advanced usage