Skip to content

task()

Popii


Popii / task

task<TState, TPayload, T>(definition): T

Defined in: define/task.ts:64

Defines a scheduled background task using Bun’s cron scheduler.

Drop the file in src/tasks/ and Popii registers it automatically. Tasks run on the specified cron schedule without blocking the event loop. They receive the full PopiiClient and, if triggered via pop.schedule(), an optional payload object.

TState = any

TPayload = unknown

T extends PopiiTaskDefinition<TState, TPayload> = PopiiTaskDefinition<TState, TPayload>

T

T

src/tasks/daily-cleanup.ts
import { task } from "popii";
export default task({
name: "daily-cleanup",
schedule: "0 3 * * *", // every day at 03:00 UTC
async run(client) {
const db = (client as any).db;
db.exec("DELETE FROM expired_sessions WHERE expires_at < ?", Date.now());
client.discord.emit("debug", "Cleaned up expired sessions");
}
});
src/tasks/send-report.ts
import { task } from "popii";
export default task({
name: "send-report",
async run(client, payload) {
const { channelId, text } = payload as { channelId: string; text: string };
const channel = client.discord.channels.cache.get(channelId);
if (channel?.isTextBased()) await channel.send(text);
}
});
// Trigger from a command:
// await pop.schedule("send-report", { channelId: "123", text: "Report ready!" });
import { task } from "popii";
export default task({
name: "fetch-stats",
schedule: "* * * * *", // every minute
retries: 3,
retryDelay: 2000,
timeoutMs: 10_000,
async run(client) {
const stats = await fetchExternalStats();
// store stats...
}
});