DEV Community

Cover image for How to create a cron job in Vercel
Cesar Muñoz
Cesar Muñoz

Posted on

How to create a cron job in Vercel

Code: https://github.com/cesmunoz/vercel-cron-example

Introduction

Vercel release a few weeks ago a feature that we were waiting for a long time ago. This feature was already on other platforms as Netlify, so I’m glad that we have it now on this platform.

A corn job is basically a work schedule that runs assignments at a certain specific time, these activities are called Cron Jobs.

Some examples of cron jobs can be:

  • send a notification to a user at 9 AM
  • do a process every 15 minutes

The schema of a cron job is the following:

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (0 is Sunday, 6 is Saturday)
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ │
# * * * * *
Enter fullscreen mode Exit fullscreen mode

For more about the schema you can check it up over here: https://crontab.guru/

Some examples of corn job periods can be:

  • Every hour = 0 * * * *
  • Every minute = * * * * *
  • Every day of the month = 0 0 1 * *
  • Every week = 0 0 * * 1

The Cron kernel is an integrated Linux functionality that schedules the execution of programs on your scheme. Cron searches the crontab (Cron tables) for previously established instructions and files. You can set up a Cron job to immediately manage code or other instructions by using a specific format.

Requirements

  • Nodejs
  • A Vercel account
  • Vercel CLI (In this example we are pushing everything directly to vercel)
npm i -g vercel
Enter fullscreen mode Exit fullscreen mode

I hope you have everything set up!. Let’s code 🙂

Create a simple project

To do it run the following commands in the terminal

mkdir cron-job-vercel
cd cron-job-vercel
npm init -y

Enter fullscreen mode Exit fullscreen mode

Then install the vercel package

npm install vercel --save-dev
Enter fullscreen mode Exit fullscreen mode

Let’s create a folder called API and inside create a file where it will be the cron job

mkdir api
touch api/hello-world.js
Enter fullscreen mode Exit fullscreen mode

In the hello-world.js paste the following code

module.exports = (req, res) => {
  res.send({
    status: 200,
    message: "Hello world!!",
  });
};
Enter fullscreen mode Exit fullscreen mode

Then add the most important thing about this to run as a cron job. VERCEL.JSON

touch vercel.json
Enter fullscreen mode Exit fullscreen mode

Cron configuration

Here you need to add the configuration of each cron job (if you have several cron jobs)

{
  "crons": [
    {
      "path": "/api/hello-world", // path of the handler
      "schedule": "* * * * *"  // configuration of the cron job
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

IMPORTANT!:
Take into consideration that if you are using your personal account (Hobby) you can have only 2 cron jobs total, and those can be triggered once per day. So adjust the example to your necessities.

Deploy to Vercel

To deploy adjust your package.json. Please add the following script:

"scripts": {
    "deploy": "vercel --prod"
},
Enter fullscreen mode Exit fullscreen mode

And in the command line type npm run deploy. Wait a few minutes and you will have a response similar to this one:

npm run deploy

> cron-job-vercel@1.0.0 deploy
> vercel --prod
Enter fullscreen mode Exit fullscreen mode

Go to vercel after the cron job starts of you run it manually and you will see something like this

Image CronJob Execution

Conclusion

Cron jobs are super useful in the development of software. Vercel makes it super easy and handy to use it.

See you next week.

Happy Coding

Ces.

Top comments (3)

Collapse
 
shinantc profile image
Shinan

Tried the same but not working. Below is my handler function:

export default async function handler(request, response) {
  try {
    // Your cron job logic goes here
    // This block will run according to the schedule specified in vercel.json
    // Replace this comment with your cron job code
  console.log("Cron job successfull (FROM HANDLER");

    // Respond with a success message
    response.status(200).send("Cron job executed successfully");
  } catch (error) {
    console.error("Error:", error);
    response.status(500).send("Internal Server Error");
  }
}
Enter fullscreen mode Exit fullscreen mode

All it has is a log. I just wanna check if it works. This function is inside a file called cron.js which is inside a folder called api. So the path is /api/cron.js.

This is my vercel.json:

{
    "version": 2,
    "builds": [
      {
        "src": "./index.js",
        "use": "@vercel/node"
      }
    ],
    "routes": [
      {
        "src": "/(.*)",
        "dest": "/"
      }
    ],
    "crons": [
      {
        "path": "/api/cron",
        "schedule": "0 10 * * *"
      }
    ]
  }
Enter fullscreen mode Exit fullscreen mode

Can you spot the mistake? The log isn't appearing even if i manually trigger the run button on vercel cron jobs. The handler isn't getting called.

Collapse
 
monfernape profile image
Usman Khalil

Looks great, thanks for the piece.

Collapse
 
emiltayeb profile image
Emil Tayeb

Looks good! i'll take a look