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 |
Publishing from cron
Combine cron with ctx.publish() to push periodic updates:
export const statsUpdate = live.cron('*/30 * * * * *', async (ctx) => {
const stats = await db.stats.aggregate();
ctx.publish('stats', 'set', stats);
});
export const stats = live.stream('stats', async () => {
return db.stats.aggregate();
}, { merge: 'set' }); Use cases
- Clean up expired data
- Poll external APIs and push results
- Aggregate metrics
- Send periodic heartbeats
Was this page helpful?