Automating Your Tasks with CRON Jobs: A Real-World Example using Next.js and Vercel🔥

Automating Your Tasks with CRON Jobs: A Real-World Example using Next.js and Vercel🔥

Learn to automate your repetitive tasks using CRON jobs, and see how a Next.js app deployed on Vercel can streamline your workflows and save you time

What are CRON Jobs? 🤔

CRON jobs are automated tasks scheduled to run on a Unix or Linux operating system at specific intervals. These tasks are set up using the CRON daemon, a time-based job scheduler in Unix-like operating systems.

A CRON job is created by specifying a schedule, which can be based on specific dates and times, or recurring intervals such as every minute, hour, day, week, or month. Once the schedule is defined, the CRON daemon will automatically run the specified command or script at the specified intervals.

The scheduling syntax is composed of 5 stars, each representing a different schedule aspect.

Example of CRON Job:-

Here is an example syntax for cron job scheduling:

*     *     *     *     *     
-     -     -     -     -     
|     |     |     |     |     
|     |     |     |     +----- day of the week (0 - 6) (Sunday=0) 
|     |     |     +------- month (1 - 12) 
|     |     +--------- day of the month (1 - 31) 
|     +----------- hour (0 - 23) 
+------------- min (0 - 59)

For instance, if you want a cron job to run every day at 6:30 AM, you can use:

30 6 * * * command_to_run

This will run the command command_to_run at 6:30 AM, every day.

Applications for CRON Job🈸

CRON jobs can be used for a variety of tasks, including system maintenance, data backups, and data processing. They are commonly used to automate repetitive tasks that would otherwise need to be done manually, saving time and effort.


How I used CRON job for a task in Next JS and Vercel🦸‍♂️

Recently while working on a side project I came across a use case where I could use CRON Job to automate the task by scheduling it to run every day instead of implementing it manually.

Here is a simple CRON Job I wrote in Next JS in src/pages/api/cron.js

import dbconnection from "@/lib/dbconn";
import Birthday from "@/models/Birthday";
import twilio from 'twilio';

dbconnection();

export default async function handler(req, res) {
    try {
        const today = new Date();
        const query = Birthday.find({ date: today }).select('name date -_id').lean().limit(5);
        const birthdays = await query.exec();
        if (birthdays.length === 0) {
            console.log(`No birthdays on ${today}`);
            res.send({ message: "No Birthdays Today" })
            return;
        }
        const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
        const messages = await Promise.all(birthdays.map(async (birthday) => {
            return client.messages.create({
                messagingServiceSid: 'MG19c8d8f851ee2e2525446fc35d1667ab',
                body: `Subramanya, Today is ${birthday.name}'s Birthday!. Don't Forget to wish🎉`,
                from: process.env.TWILIO_PHONE_NUMBER,
                to: process.env.MY_ACTUAL_NUMBER,
            });
        }));
        messages.forEach((message, index) => {
            console.log(`Sent message to ${birthdays[index].name} at ${birthdays[index].date}: ${message.sid}`);
        });
        res.send({ message: "All message sent successfully." })
    } catch (error) {
        console.error(error);
    }
}

Here's what this code does:- The above CRON job is a script that runs daily to send a message to me whose birthday is on the current day. This script uses the CRON daemon to schedule the job to run every day at a specific time.

The script connects to a database using the "dB connection" function and queries the "Birthday" model for birthdays that match the current date. If there are no birthdays, it sends a message saying there are no birthdays. If there are birthdays, the script sends a message to me (reminding me to wish that person😅) using Twilio's messaging service.

The messages are sent using the Twilio API and include a personalized message for each recipient. The script logs each message sent and returns a response indicating that all messages were sent successfully.

Overall, this CRON job automates the process of sending birthday messages, saving time and effort by eliminating the need to send messages manually.

This CRON Job is written in Next JS and I have deployed this using Vercel. Vercel by default supports CRON Job.

Once after implementing the actual CRON Job, you can add the following snippet in vercel.json before deploying...

{
    "crons": [{
      "path": "/api/cron",
      "schedule": "0 6 * * *"
    }]
  }

Here's a general overview of the steps you can follow to set up a CRON job in your Next.js app on Vercel:

  1. Create a new serverless function in your Next.js app that will execute your CRON job. This function should contain the code for your CRON job and should be configured to run at the desired schedule.

  2. You can use the built-in scheduling feature of Vercel's platform to schedule your function to run at specific intervals.

  3. Deploy your app to Vercel and ensure that your serverless function is included in the deployment.

  4. Monitor your CRON job's performance using Vercel's built-in monitoring tools and logs.

Overall, setting up a CRON job in a Next.js app on Vercel requires a bit of configuration and setup, but it's generally straightforward and can save you time and effort by automating repetitive tasks.

For example, I have scheduled this CRON job to run every day at 6 AM using the scheduling syntax we specified earlier as follows:-

Even though vercel's CRON Jobs features are still in beta, it works perfectly. I've scheduled this CRON Job and it seems to be working perfectly. If you run into some problems you can definitely make use of logs which is one of the best features that make vercel stand out. For example, initially, I ran into some problems with CRON Jobs but logs made it easier for me to debug those errors and fix them🔨.

Conclusion

In conclusion, CRON jobs are an incredibly useful feature for automating repetitive tasks and streamlining your workflows. By using CRON jobs, you can schedule specific tasks to run at a particular time or interval, freeing up your time to focus on other important aspects of your work.

In this blog post, we've seen how to build a CRON job using Next.js and deploy it using Vercel. With Vercel's built-in support for CRON jobs, it's easy to set up automated tasks and run them on a schedule without the need for additional services or infrastructure.

As a Next.js developer, you have access to a powerful toolset that can help you build complex applications quickly and easily. By leveraging CRON jobs and other features of Next.js, you can create robust, scalable applications that meet the needs of your users.

So what are you waiting for? Try out CRON jobs and see how they can make your life easier. And if you have any feedback or suggestions, feel free to share them in the comments below. Thanks for reading!