Pages Functions Cron Triggers & Scheduled Tasks
In this tutorial, you'll learn about Pages Functions Cron Triggers & Scheduled Tasks. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
This tutorial explains how to schedule recurring tasks in Cloudflare Pages Functions using cron triggers, enabling automated cleanup, report generation, and data synchronization without maintaining a separate server. Serverless scheduled tasks run at the edge and scale to zero when not executing. The DodaTech analytics system uses a daily cron trigger to aggregate page view data and store summaries in D1.
Cron Trigger Basics
Cron triggers run a Pages Function on a schedule defined by a cron expression. You configure the trigger in your wrangler.toml file or the Cloudflare dashboard.
flowchart LR A[Cron schedule] --> B[Trigger event] B --> C[Execute function] C --> D[Process data] D --> E[Store result] D --> F[Send notification] style B fill:#f90,color:#fff style C fill:#f90,color:#fff
Defining a Cron Trigger
Create a function that listens for scheduled events. The function receives a ScheduledEvent with information about the trigger.
// functions/_scheduled.js
export async function onRequest(context) {
console.log('Scheduled function running at:', new Date().toISOString());
const now = Date.now();
const yesterday = new Date(now - 86400000).toISOString().split('T')[0];
const { results } = await context.env.DB.prepare(
'SELECT path, count(*) as visits FROM page_views WHERE date = ? GROUP BY path'
).bind(yesterday).all();
for (const row of results) {
await context.env.DB.prepare(
'INSERT INTO daily_summary (path, visits, date) VALUES (?, ?, ?)'
).bind(row.path, row.visits, yesterday).run();
}
console.log('Processed ' + results.length + ' pages for ' + yesterday);
return new Response('OK');
}
// Expected console output:
// Scheduled function running at: 2026-06-23T02:00:00.000Z
// Processed 42 pages for 2026-06-22
Cron Expression Patterns
Cron triggers use standard five-field cron expressions. Configure the schedule in your Pages project settings.
// Validate a cron expression
function validateCron(expression) {
const parts = expression.trim().split(/\s+/);
if (parts.length !== 5) {
return { valid: false, error: 'Cron expression must have exactly 5 fields' };
}
const fieldNames = ['minute', 'hour', 'day-of-month', 'month', 'day-of-week'];
for (let i = 0; i < parts.length; i++) {
if (!/^[\d\*\-\/\,]+$/.test(parts[i])) {
return { valid: false, error: 'Invalid character in ' + fieldNames[i] + ' field' };
}
}
return { valid: true, expression: expression, description: describeCron(parts) };
}
function describeCron(parts) {
const descriptions = {
'0 2 * * *': 'Runs daily at 2:00 AM UTC',
'*/15 * * * *': 'Runs every 15 minutes',
'0 0 * * 0': 'Runs weekly on Sunday at midnight',
'0 0 1 * *': 'Runs monthly on the 1st at midnight'
};
return descriptions[parts.join(' ')] || 'Custom schedule';
}
console.log(validateCron('0 2 * * *'));
// Expected output:
// { valid: true, expression: '0 2 * * *', description: 'Runs daily at 2:00 AM UTC' }
Data Cleanup Task
Use scheduled functions to remove old data and keep your database within storage limits.
// functions/_scheduled-cleanup.js
export async function onRequest(context) {
const thirtyDaysAgo = new Date(Date.now() - 30 * 86400000).toISOString();
const deletedSessions = await context.env.DB.prepare(
'DELETE FROM user_sessions WHERE last_active < ?'
).bind(thirtyDaysAgo).run();
const deletedLogs = await context.env.DB.prepare(
'DELETE FROM request_logs WHERE timestamp < ?'
).bind(thirtyDaysAgo).run();
console.log('Cleanup complete');
console.log('Sessions removed: ' + deletedSessions.meta.changes);
console.log('Log entries removed: ' + deletedLogs.meta.changes);
if (deletedSessions.meta.changes > 0 || deletedLogs.meta.changes > 0) {
await context.env.KV.put('last-cleanup', new Date().toISOString());
}
return new Response('Cleanup completed');
}
// Expected console output:
// Cleanup complete
// Sessions removed: 128
// Log entries removed: 4532
FAQ
Practice Questions
- What five fields does a standard cron expression contain?
- Which HTTP status code should a scheduled function return on success?
- What environment variable is available in scheduled functions that indicates the trigger time?
Summary
Cron triggers in Cloudflare Pages Functions run scheduled tasks at the edge without managing servers. Configure them with five-field cron expressions for intervals as low as one minute. Use scheduled functions for data aggregation, cleanup, report generation, and synchronization tasks.
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro — security-first tools for the modern web.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro