Scheduling Cron Jobs
Run tasks on a schedule with router.cron()
Schedule recurring tasks using cron expressions. Schedules are defined in code, deployed with your agents, and automatically provisioned.
Routes Location
All routes live in src/api/. Import agents you need and call them directly.
Basic Example
import { createRouter } from '@agentuity/runtime';
import reportGenerator from '@agent/report-generator';
const router = createRouter();
router.cron('0 9 * * *', async (c) => { // runs daily at 9am
c.var.logger.info('Daily report starting');
const report = await reportGenerator.run({
type: 'daily',
date: new Date().toISOString(),
});
await c.var.kv.set('reports', `daily-${Date.now()}`, report);
return c.text('OK');
});
export default router;Cron Syntax
Standard five-field cron format:
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sunday=0)
│ │ │ │ │
* * * * *Common Schedules
| Schedule | Expression | Useful for |
|---|---|---|
| Every 5 minutes | */5 * * * * | Health checks, quick sync |
| Hourly | 0 * * * * | Aggregations, cleanup, etc. |
| Daily at 9am | 0 9 * * * | Reports, notifications, etc. |
| Weekly (Sunday midnight) | 0 0 * * 0 | Weekly summaries, etc. |
| Monthly (1st at midnight) | 0 0 1 * * | Monthly reports, etc. |
Full Example
A health check that monitors external services and stores results:
import { createRouter } from '@agentuity/runtime';
import healthChecker from '@agent/health-checker';
const router = createRouter();
router.cron('*/5 * * * *', async (c) => { // runs every 5 minutes
const startTime = Date.now();
c.var.logger.info('Health check starting');
try {
const status = await healthChecker.run({
services: ['api', 'database', 'cache'],
});
await c.var.kv.set('monitoring', 'latest-health', {
...status,
checkedAt: new Date().toISOString(),
durationMs: Date.now() - startTime,
});
c.var.logger.info('Health check completed', { status });
return c.text('OK');
} catch (error) {
c.var.logger.error('Health check failed', { error });
return c.text('ERROR', 500);
}
});
export default router;Testing Locally
Cron jobs only trigger in deployed environments. For local testing, add a manual POST route:
import dailyReport from '@agent/daily-report';
router.cron('0 9 * * *', cronHandler);
// Manual trigger for local development
router.post('/trigger', async (c) => {
return cronHandler(c);
});
async function cronHandler(c) {
const result = await dailyReport.run({ date: new Date() });
return c.json(result);
}Best Practices
- Log job start and completion for debugging scheduled tasks
- Use
c.var.kvor object storage to persist results for later inspection - Handle errors gracefully so one failure doesn't break the schedule
- Keep jobs idempotent when possible, in case of retries
Standalone Usage
Cron jobs work without agents. This example clears expired cache entries hourly:
import { createRouter } from '@agentuity/runtime';
const router = createRouter();
router.cron('0 * * * *', async (c) => {
const allKeys = await c.var.kv.getKeys('cache');
const expiredKeys = allKeys.filter(key => key.startsWith('temp-'));
for (const key of expiredKeys) {
await c.var.kv.delete('cache', key);
}
c.var.logger.info('Cache cleanup completed', { deleted: expiredKeys.length });
return c.text('OK');
});
export default router;Next Steps
- HTTP Routes: Standard request/response endpoints
- Email Handling: Process incoming emails
- Key-Value Storage: Store job results
Need Help?
Join our Community for assistance or just to hang with other humans building agents.
Send us an email at hi@agentuity.com if you'd like to get in touch.
Please Follow us on
If you haven't already, please Signup for your free account now and start building your first agent!