Cron - live.cron()
Run scheduled tasks on the server.
// src/live/cleanup.js
import { live } from 'svelte-realtime/server';
export const cleanup = live.cron('*/5 * * * *', async (ctx) => {
const deleted = await db.sessions.deleteExpired();
console.log(`Cleaned up ${deleted} expired sessions`);
}); Schedule format
Standard cron syntax: minute hour day month weekday
| Expression | Meaning |
|---|---|
* * * * * | Every minute |
*/5 * * * * | Every 5 minutes |
0 * * * * | Every hour |
0 0 * * * | Daily at midnight |
0 0 * * 1 | Every Monday at midnight |
Auto-publish to a topic
Pass a topic name as the second argument. The cron function publishes its return value as a set event on that topic:
export const refreshStats = live.cron('*/5 * * * *', 'stats', async () => {
return { users: await db.users.count(), orders: await db.orders.todayCount() };
}); Pair it with a merge: 'set' stream:
export const stats = live.stream('stats', async (ctx) => {
return db.stats();
}, { merge: 'set' }); Publishing from cron with ctx.publish
The function receives a ctx object with publish, throttle, debounce, and signal - the same helpers available in RPC handlers (minus user and ws, since cron runs outside a connection). Use ctx.publish for fine-grained control, e.g. publishing individual created/deleted events on a crud stream:
export const cleanup = live.cron('0 * * * *', 'boards', async (ctx) => {
const stale = await listStaleBoards();
for (const board of stale) {
await deleteBoard(board.board_id);
ctx.publish('boards', 'deleted', { board_id: board.board_id });
}
// returning undefined skips the automatic 'set' publish
}); If the function returns a value, it is published as a set event. If it returns undefined, no automatic publish happens - this lets you use ctx.publish exclusively without an unwanted set event overwriting your crud updates.
Platform capture
The platform is captured automatically from the first RPC call. If your app starts cron jobs before any WebSocket connections, call setCronPlatform(platform) in your open hook:
import { setCronPlatform } from 'svelte-realtime/server';
export function open(ws, { platform }) {
setCronPlatform(platform);
} Use cases
- Clean up expired data
- Poll external APIs and push results
- Aggregate metrics
- Send periodic heartbeats
Was this page helpful?