Cron jobs
How to add scheduled tasks with small, practical examples.
AI Skill for cron-jobs
Prompt: Type
/cron-jobs in your Copilot / Cursor or other chat to use skill with the provided context./cron-jobs Add or update a cron task for this project. Requirements: - Create task in src/lib/cron/tasks and export it from the task index. - Keep business logic in service layer helpers. - Use Promise chaining (.then/.catch) instead of async/await in task run functions.
What you need
- Enable cron jobs in
src/config/app.ts. - Create a task file in
src/lib/cron/tasks/. - Export it from
src/lib/cron/tasks/index.ts. - Your task will be scheduled automatically.
Enable cron jobs
Make sure cron jobs are enabled in your configuration file src/config/app.ts:
// src/config/app.ts
// ...
cron: {
enabled: true,
},
// ...Create a task file
Create src/lib/cron/tasks/sync-external-data.task.ts:
import { syncExternalData } from '@/lib/services/cron-tasks';
export const syncExternalDataTask = {
name: 'syncExternalData',
schedule: '*/15 * * * *',
run: () =>
syncExternalData().then((result) => {
console.info('sync done', result);
}),
};Add it to task index
Update src/lib/cron/tasks/index.ts:
import { syncExternalDataTask } from './sync-external-data.task';
export const cronTasks = [syncExternalDataTask];Add business logic in service layer
Keep reusable logic in src/lib/services/cron-tasks.ts so the same function can also be used by oRPC and Server Actions.
export function syncExternalData() {
return fetch('https://example.com/api/sync').then((res) => res.json());
}Common schedules
- Every 15 minutes:
*/15 * * * * - Every hour:
0 * * * * - Every day at 02:00:
0 2 * * * - Every Monday at 09:00:
0 9 * * 1
Full minimal example
// src/lib/cron/tasks/cleanup.task.ts
export const cleanupTask = {
name: 'cleanup',
schedule: '0 2 * * *',
run: () =>
Promise.resolve()
.then(() => {
// your cleanup logic
})
.catch((error) => {
console.error('[cron] cleanup failed', error);
}),
};// src/lib/cron/tasks/index.ts
import { cleanupTask } from './cleanup.task';
import { syncExternalDataTask } from './sync-external-data.task';
export const cronTasks = [syncExternalDataTask, cleanupTask];