# Cron 触发器模式
## API 数据同步
typescript
export default {
async scheduled(controller, env, ctx) {
const response = await fetch("https://api.example.com/data", {headers: { "Authorization": `Bearer ${env.API_KEY}` }});
if (!response.ok) throw new Error(`API 错误: ${response.status}`);
ctx.waitUntil(env.MY_KV.put("cached_data", JSON.stringify(await response.json()), {expirationTtl: 3600}));
},
};
## 数据库清理
typescript
export default {
async scheduled(controller, env, ctx) {
const result = await env.DB.prepare(`DELETE FROM sessions WHERE expires_at = ? ORDER BY date`).bind(startOfWeek.toISOString()).all();
const report = {period: "weekly", totalRevenue: results.reduce((sum, d) => sum + d.revenue, 0), totalOrders: results.reduce((sum, d) => sum + d.orders, 0), dailyBreakdown: results};
const reportKey = `reports/weekly-${Date.now()}.json`;
await env.REPORTS_BUCKET.put(reportKey, JSON.stringify(report));
ctx.waitUntil(env.SEND_EMAIL.fetch("https://example.com/send", {method: "POST", body: JSON.stringify({to: "
[email protected]", subject: "每周报告", reportUrl: `https://reports.example.com/${reportKey}`})}));
},
};
## 健康检查
typescript
export default {
async scheduled(controller, env, ctx) {
const services = [{name: "API", url: "https://api.example.com/health"}, {name: "CDN", url: "https://cdn.example.com/health"}];
const checks = await Promise.all(services.map(async (service) => {
const start = Date.now();
try {
const response = await fetch(service.url, { signal: AbortSignal.timeout(5000) });
return {name: service.name, status: response.ok ? "up" : "down", responseTime: Date.now() - start};
} catch (error) {
return {name: service.name, status: "down", responseTime: Date.now() - start, error: error.message};
}
}));
ctx.waitUntil(env.STATUS_KV.put("health_status", JSON.stringify(checks)));
const failures = checks.filter(c => c.status === "down");
if (failures.leng