Reputation: 35100
I've been trying to schedule background jobs in a Next.js application deployed on Vercel using the node-cron library, but I'm encountering an issue where the scheduled jobs are not being executed. I've followed the documentation and some online guides, but I'm still facing this problem.
Here's a simplified version of the code I'm using:
// pages/api/scheduled-job.ts
import { NextApiRequest, NextApiResponse } from 'next'
import cron from 'node-cron'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const schedule = '* * * * *' // Run every minute
const job = () => {
console.log('Scheduled job is running every minute...')
}
cron.schedule(schedule, job)
res.status(200).send('Scheduled job has been set up.')
}
Here are the steps I've taken and the things I've checked:
I'm wondering if there might be some compatibility issue with Vercel or if there's something specific to Next.js or node-cron that I'm missing. If anyone has experience with scheduling jobs in a Next.js application on Vercel, I'd greatly appreciate any insights or suggestions to troubleshoot this issue.
Thank you in advance for your help! If there's any additional information needed, please let me know.
Upvotes: 0
Views: 6471
Reputation:
Please see this guide for cron job on vercel. https://vercel.com/guides/how-to-setup-cron-jobs-on-vercel
Only two cron jobs can be run on Hobby plan and it also run once a day.
Upvotes: 0
Reputation: 4146
Next.js comes with inbuilt support for cron on Vercel.
You don't need to use node-cron
, and nor shall it work on Vercel.
Vercel supports cron jobs for Serverless and Edge Functions. Cron jobs can be added through vercel.json or the Build Output API.
https://vercel.com/docs/cron-jobs
So you just need to have a vercel.json
file at the root, listing the schedule and the api paths to hit.
"crons": [
{
"path": "/api/scheduled-job",
"schedule": "* * * * *"
},
...
],
For reference: https://github.com/vercel/examples/blob/main/solutions/cron/vercel.json
Upvotes: 0