Tasks & Jobs
Modern applications frequently require background processing — whether running periodic cleanup routines, generating nightly reports, or invalidating a cache on a schedule. Harpia provides a structured approach for defining and scheduling Tasks using the cron library.
Creating a Task
Tasks are located in the app/tasks/ directory. You can generate a new task scaffold quickly using the CLI:
bun harpia generate task cleanup
Alternatively, using the shorthand:
bun g task cleanup
This generates a new file (cleanup.ts) in app/tasks/, pre-configured with a CronJob instance:
// app/tasks/cleanup.ts
import { CronJob } from "cron";
function task() {
console.log("Task executed at:", new Date().toISOString());
}
export const cleanup = new CronJob(
"0 0 * * *", // Cron expression — runs daily at midnight
task, // Function to execute
null, // Callback when the job is stopped (optional)
false, // Auto-start? Keep false — the TaskManager handles this
"UTC" // Timezone (optional)
);
[!TIP] You can use crontab.guru to build and validate your cron expressions interactively.
Registering a Task
After creating a task, you must register it in the central TaskManager located at app/tasks/index.ts. Simply import your task and add it to the jobs array:
// app/tasks/index.ts
import type { CronJob } from "cron";
import { cleanup } from "./cleanup";
class TaskManager {
private jobs: CronJob[];
constructor() {
this.jobs = [
cleanup,
// Add more tasks here as your application grows
];
}
public run() {
for (const job of this.jobs) {
job.start();
}
}
}
export const Tasks = new TaskManager();
The TaskManager is instantiated once and its run() method is called during the server boot phase (start/server.ts), which triggers job.start() on every registered CronJob.
[!NOTE] If you scaffolded your project using
create-harpia-app,Tasks.run()is already called automatically insidestart/server.ts. You do not need to invoke it manually — just register your tasks in thejobsarray and they will start alongside the server.
Cron Expression Reference
A cron expression has five fields:
┌────────── minute (0–59)
│ ┌──────── hour (0–23)
│ │ ┌────── day of month (1–31)
│ │ │ ┌──── month (1–12)
│ │ │ │ ┌── day of week (0–7, where 0 and 7 are Sunday)
│ │ │ │ │
* * * * *
Common examples:
| Expression | Meaning |
|---|---|
* * * * * | Every minute |
0 * * * * | Every hour |
0 0 * * * | Every day at midnight (UTC) |
0 9 * * 1 | Every Monday at 09:00 |
0 0 1 * * | First day of every month |