Task
Task
Represents a task instance with execution logic and metadata.
Tasks can be scheduled to run at specific times or intervals using cron expressions or date-based scheduling. They support preparation logic to conditionally execute and provide a context for accessing CommandKit and Discord.js functionality.
Example
import { task } from '@commandkit/tasks';
export default task({
name: 'cleanup-old-data',
schedule: { type: 'cron', value: '0 2 * * *' }, // Daily at 2 AM
async prepare(ctx) {
// Only run if there's old data to clean
return await hasOldData();
},
async execute(ctx) {
await cleanupOldRecords();
await ctx.commandkit.client.channels.cache
.get('log-channel')?.send('Cleanup completed!');
},
});
class Task<T extends Record<string, any> = Record<string, any>> {
constructor(data: TaskDefinition<T>)
immediate: boolean
name: string
schedule: TaskSchedule | null
isCron() => boolean;
isDate() => boolean;
timezone: string | undefined
prepare(ctx: TaskContext<T>) => Promise<boolean>;
execute(ctx: TaskContext<T>) => Promise<void>;
}
constructor
(data: TaskDefinition<T>) => Task
Creates a new task instance.
immediate
boolean
Whether this task should run immediately when created. Only applicable to cron tasks, defaults to false.
name
string
The unique identifier for this task.
schedule
TaskSchedule | null
The schedule configuration for this task. Returns null if no schedule is defined (manual execution only).
isCron
() => boolean
Checks if this task uses cron-based scheduling.
isDate
() => boolean
Checks if this task uses date-based scheduling.
timezone
string | undefined
The timezone for the task schedule. Returns undefined if no timezone is defined.
prepare
(ctx: TaskContext<T>) => Promise<boolean>
Determines if the task is ready to be executed.
This method calls the optional prepare function if defined. If no prepare function is provided, the task is always ready to execute.
execute
(ctx: TaskContext<T>) => Promise<void>
Executes the task's main logic.
This method calls the execute function defined in the task definition. It provides access to the CommandKit instance, Discord.js client, and any custom data passed to the task.