我的应用程序定期运行一个功能,运行时间约为 20 分钟。
这在开发中很好。但是当我在 Vercel 上部署该应用程序时,该功能并未完成。
这是因为 Vercel 允许函数执行最多 10 秒的限制。我怎样才能运行这个功能?
截至 2023 年 10 月,接受的答案不正确。
您可以通过从函数导出 maxDuration 将超时增加到最多 5 分钟:
export const maxDuration = 300 // set a custom timeout in seconds, maximum 5 minutes (300s)
在此处阅读更多信息:https://vercel.com/changelog/serverless-functions-can-now-run-up-to-5-minutes
使用应用程序路由器 (
/app/api/my-function/route.ts
):
export const maxDuration = 5; // 5 seconds
export const dynamic = 'force-dynamic';
export function GET(request: Request) {
return new Response('{}', { status: 200 });
}
使用页面路由器 (
/pages/api/my-function/handler.ts
):
export const config = {
maxDuration: 5, // 5 seconds
};
export default function handler(
request: NextApiRequest,
response: NextApiResponse,
) {
response.status(200).json({});
}
如果您想在使用 Vercel 时覆盖整个项目的函数的最大持续时间,您可以在
vercel.json
中完成:
{
"functions": {
"app/api/**/*": {
"maxDuration": 5
}
}
}
您可以在官方文档上阅读更多相关信息。
不幸的是,如果您想继续将 nextjs 与 Vercel 一起使用,您无能为力。您可以将其托管在 aws amplify 中,但是到此答案时,lambda 函数还不能在 nextjs 12 中开箱即用。还有其他服务可以帮助您将其托管在 aws 中,但老实说,您应该更好要么不使用 nextjs api 路由,要么,如果您确实想使用它,请创建一个外部应用程序来执行由 nextjs 函数触发的长流程,并直接从客户端向该应用程序或某些数据库请求结果。
这是 Vercel 针对该问题的解决方案,在这种情况下并不是很有帮助 https://vercel.com/guides/what-can-i-do-about-vercel-serverless-functions-timing-out