定时任务可控制是否完成再返回

This commit is contained in:
mtvpls
2026-03-01 16:07:22 +08:00
parent 95c920e565
commit fe1f79b273
2 changed files with 21 additions and 6 deletions

View File

@@ -339,6 +339,7 @@ dockge/komodo 等 docker compose UI 也有自动更新功能
| USERNAME | 站长账号 | 任意字符串 | 无默认,必填字段 |
| PASSWORD | 站长密码 | 任意字符串 | 无默认,必填字段 |
| CRON_PASSWORD | 定时任务 API 访问密码(用于保护 /api/cron 端点) | 任意字符串 | mtvpls |
| CRON_WAIT_FOR_COMPLETION | 定时任务接口是否等待任务完全结束后再返回响应true 时返回 200false 时立即返回 202 | true/false | false |
| CRON_USER_BATCH_SIZE | 定时任务用户批处理大小(控制并发处理的用户数量,影响播放记录和收藏更新任务的并发性能) | 正整数 | 3 |
| SITE_BASE | 站点 url | 形如 https://example.com | 空 |
| NEXT_PUBLIC_SITE_NAME | 站点名称 | 任意字符串 | MoonTV |

View File

@@ -58,13 +58,27 @@ export async function GET(
// 更新最后执行时间
lastExecutionTime = now;
cronJob();
// 环境变量控制是否等待定时任务完全结束后再返回响应(默认 false
// 用于防止 Vercel 等平台杀后台进程
const waitForCompletion = process.env.CRON_WAIT_FOR_COMPLETION === 'true';
return NextResponse.json({
success: true,
message: 'Cron job executed successfully',
timestamp: new Date().toISOString(),
});
if (waitForCompletion) {
// 等待定时任务完成后再返回 200
await cronJob();
return NextResponse.json({
success: true,
message: 'Cron job executed successfully',
timestamp: new Date().toISOString(),
});
} else {
// 立即返回 202定时任务在后台执行
cronJob();
return NextResponse.json({
success: true,
message: 'Cron job accepted and running in background',
timestamp: new Date().toISOString(),
}, { status: 202 });
}
} catch (error) {
console.error('Cron job failed:', error);