Understanding Crons Through Twilio: A Love Story

May 02, 2022 | By Brendan Williams

At FloQast, our app performs many tasks that are executed by crons. Crons are long-running processes that allow you to execute code at specific time intervals. They're great for automating recurring tasks like sending app notifications, or backing up databases.

The Problem

I had worked within code knowing that it was being executed by a cron. I understood what a cron was in theory but I hadn't actually created a cron project myself. So, I decided to set aside time to learn more about the process. However, it was getting close to Valentine's Day and I hadn't come up with a gift yet for my partner. So, unfortunately, I didn't have a lot of spare time to spend learning about crons.

After spending time jumping back and forth between learning about crons and thinking of gift ideas, and not being satisfied with the time devoted to either, I started thinking of alternative ideas. How could I learn about crons and get a gift at the same time?

I started thinking of gifts that could be executed by a cron. I thought sending regularly scheduled Valentine's messages throughout the day could be nice, so I looked up text messaging APIs that could help with that. I came across the Twilio API and thought it would be perfect to automate my texts. I finally had a way to accomplish both of my goals at the same time.

Here are the steps I took to create a cron project to send my partner surprise Valentine's texts hourly.

Learning Cron Expressions

Crons can be created on AWS for large-scale applications. Since this was going to be a small project, I decided to use the node-cron package for my cron. The node-cron docs describe this package as a "tiny task scheduler in pure JavaScript for node.js based on GNU crontab. This module allows you to schedule tasks in node.js using full crontab syntax." So, what is this syntax they're speaking of?

The cron syntax is an expression we write to set the execution frequency of our code. The cron expression provides space for specific fields you can edit. To explain, let's start off with the code below:

const cron = require('node-cron');

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});

The asterisks identify the scheduling fields and can be edited with the values shown below from the node-cron docs:

Here are some examples of how changes to the expression would translate to different code execution frequencies.

If we edited this schedule to 0 * * * * it would run at minute 0 of every hour.

To send every day at 10AM, we could change it to 0 10 * * *.

Every Monday at 10AM would be written as 0 10 * * 1.

We used the 1 index for Monday, but we could make it less cryptic by providing the weekday name(s) instead. We could also provide multiple values separated by commas, such as 0 10 * * 1,2 for every Monday and Tuesday at 10AM.

Dashes provide the ability to run for specific ranges, such as 0 10 * * 1-5 for Monday thru Friday at 10AM.

Finally, step values allow us to add more specificity to ranges by using "/." So, if we wanted to change our last schedule to be "10AM every other day between Monday and Friday," we would change it to 0 10 * * 1-5/2.

The node-cron documentation does a great job explaining all of the options you have. If you'd like to experiment with the syntax, https://crontab.guru has a very helpful editor that translates the expressions into readable sentences for you.

For my small messaging app, it wouldn't be running all the time, so I decided to just keep the schedule to 0 * * * * so it'd run at minute zero of every hour I'd have the app running.

Setting up Twilio

Now that I had my cron schedule, I started setting up what I'd need to send Twilio messages. I first had to go to https://www.twilio.com/try-twilio to sign up for a Twilio account. A Twilio account gives us all we need to start using their API to send texts: an account SID, auth token, and a Twilio phone number.

Twilio has great documentation that made the initial setup very clear and straightforward. After installing the twilio package and going to their Send Messages with API doc, I was able to use their quickstart code to enter my account credentials and get my app almost ready to go.

There was one remaining hard part. I had to verify my partner's phone number with Twilio. Twilio sends a verification text to the number you provide, and of course, I couldn't let her see that. I had to come up with something creative to say to use her phone for a minute.

Once I had control of her phone, I figured I'd take the extra step of creating a new contact for the Twilio phone number, named "Happy Valentine's Day from Brendan" so the upcoming messages wouldn't be seen as spam.

The Code

With the cron schedule set, and my Twilio account all active, I had everything I needed to start coding the project.

After putting my Twilio account credentials into a config.js, and the messages I wanted to say into an array exported from messages.js, I was able to set up my app.js like so:

const cron = require('node-cron');
const config = require('./config');
 
const accountSid = config.ACCOUNT_SID;
const authToken = config.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
 
const messages = require('./messages');

const job = cron.schedule('0 * * * *', () => {
   sendMessage();
});

let currentMessage = 0;
function sendMessage() {
   client.messages
       .create({
           body: messages.texts[currentMessage],
           from: config.TWILIO_NUMBER,
           to: config.RECEIPIENT_NUMBER
       })
       .then(messages => {
           console.log(`Sent: ${currentMessage} - ${messages[currentMessage]}`)
           currentMessage++
           if (currentMessage >= messages.MAX_TEXTS) {
               job.stop();
           }
       });
}

I ran the app locally and the texts successfully went out to surprise my partner every hour. Since I was just sitting there, not even on my phone, she kept asking "how are you doing this?!"

So, the moral of the story is, when you want to grow as a developer, but special days are approaching and you need to come up with a gift…why not develop the gift?

Brendan Williams
Brendan Williams is a Senior Software Engineer at FloQast. He loves solving complex problems with creative solutions and learning about the latest technologies. When not coding, he can be found enjoying time with his family and engaging in serious conversations about comic book movies.

Check out research, videos, case studies, and more!

Learn more about working at FloQast!