Automating Tasks with Cron Jobs and NestJs.

Prince Igwenagha
6 min readJan 16, 2023
Photo by Andrew Seaman on Unsplash

Most web applications these days execute a task based on the user’s request. If the user wants to get something done at a specific time, they’d have to click a button on the application. If they wanted to execute the same task again at the same time as they did initially, they would have to click the same button that sends a request to a server.

For example, let’s assume you are the owner of a restaurant. You have a solid customer base; let’s say you have about 100 rooted customers for your restaurant, and you have already established a good customer relationship with every single one of them by getting their personal details, such as their name, age, date of birth, and so on, with a CRM software. Now there’s the saying that goes like, “Everyday is someone’s birthday," and as the kind business person that you are, you love to send birthday greetings to your customers whenever it’s their birthday, but there is a problem. You can’t manually send greetings to every single customer because of any of the following reasons:

  • You will most likely forget to do so, even if you have a record of birthdays.
  • You may commit some errors when doing such with multiple customers that have the same birthdays. Imagine sending to Peter, “Birthday wishes from Delicious cakes, may your heart desires come through. Do have a lovely day, John.” Imagine the look on Peter’s face when he reads that.

With cron jobs, you can automate these kinds of tasks. They are similar to events; the only difference is that while events are based on actions, cron jobs are based on time. To learn how you can work with events and NestJs, check out the article:

Now you get the idea behind cron jobs. A cron job is a program that’s used to schedule tasks that are to be executed repeatedly at a specific time.

With cron operators, you can define the time to execute jobs. Some of these operators include:

  • Asterisks (*)
  • Comma (,)
  • Hyphen (-)
  • Slash (/)

Syntax and Semantics of Asterisks:

This operator is used to represent every value that can be used in a crontab field. The format of a crontab is given as:

second   minute   hour   day(month)   month    day(week)

The representation of the fields with asterisks is given as:

* * * * *

This simply means that a cron job will be executed every day of the week, every month, every day of each month, every hour, every minute, and every second. Now if you wanted to be specific with your timing, you could write something as;

 * * * 5 * 3

This simply means that you want your task to be executed whenever it is Wednesday (3), and if that day happens to be the 5th day of every month. This task will be executed every second, minute, and hour of that specified day.

Syntax and Semantics of Commas:

With this operator, you can use multiple values in a field. Here is an example;

* * * 5,7 * 3,2

This means that you want your tasks executed on Tuesdays and Wednesdays, if they happen to be the 5th and 7th day of every month, and this task will be executed at every second, minute, and hour of those days.

Syntax and Semantics of Hyphens:

With this operator, you can execute tasks on the basis of ranges. For example, if you wanted to execute your tasks from Wednesdays to Sundays of every month, day, minute, and second, you could write:

* * * * * 3-0

Syntax and Semantics of Slash:

Things get a little bit complex with the slash. Example, with the syntax:

* * */4 * * 0

This means that you want your task executed on Sundays, once every 4 hours, every minute, and every second of that day. That wasn’t so hard, was it?

The Linux OS is the origin of these operators, and with them you can be certain your tasks will be executed automatically at the specified time… but we are not going into Linux, are we?

To illustrate this with NestJs, I’ll be using the same old repo I’ve been using for most of my previous articles. You can clone it to follow along. To write cron jobs in Nest, you will need to install two packages from your project’s terminal:

npm install --save @nestjs/schedule
npm install --save-dev @types/cron

Don’t forget to docker-compose build if you’re working with Docker.

Although the food_demo API is less of a restaurant API, you could create a user entity; containing a birthday field; that stores user info, we could also write a cron job that sends a greeting to the user whenever it’s their birthday. However, this is not the best option for this article. So we will write 4 simple cron jobs that will be executed within a short time-frame, using different operators:

  • A task that sends a message saying “Delicious cakes is open for business”, once the second reads 0.
  • A task that sends a message saying “Delicious cakes is still taking orders”, every 5 seconds.
  • A task that sends a message saying “Delicious cakes will be closing soon”, once the second reads 40 or 45.
  • A task that sends a message saying “Delicious cakes is closed for the day”, once the second reads 50.

ILLUSTRATION

  • Once the packages are installed, activate job scheduling by importing “ScheduleModule” class in the app.module.ts file.
  • Create a new folder named “cronjobs” and its service file with the commands:
nest generate module cronjobs
nest generate service cronjobs

This folder registers automatically in the app.module.ts file as well.

For the first task which sends a message saying “Delicious cakes is open for business”, once the second reads 0, this can be done with the snippet, in its service.ts file:

This imports the Cron decorator which is used to create a cron job with the “openForBusiness” method. On the first second of every minute, the message “Delicious cakes is open for business…” is printed in the project’s terminal.

For the task which sends a message saying “Delicious cakes is still taking orders”, every 5 seconds; it can be done with the code:

Once every 5 seconds, the “Delicious cakes is still taking orders” message is printed in the terminal. Nest provides a different method of printing the message in a more expressive manner, with the “CronExpression” enum class.

Other variables of the class include:

For the task which sends a message saying “Delicious cakes will be closing soon”, once the second reads 40 or 45, this is done with the code:

Changes can be observed in the terminal:

Now for the last task which sends a message saying “Delicious cakes is closed for the day”, once the second reads 50, recall that the “takingOrders” task runs every 5 seconds, and you don’t want to take orders while you are closed, right? Here, you will add little functions that stop the “takingOrders” job once the second reads 50, and also restart the job once you are open for business. This can be done in the following way:

Here the “SchedulerRegistry” class is imported. It helps you make reference to a named cron job with the “getCronJob()” method. The cron job for taking orders is named “takingOrders”, and it is then called and stopped in the “closed” job. This job restarts in the “openForBusiness” cron job, and Delicious cakes is back in business.

Changes can be observed in the terminal:

What other task do you have in mind? You can schedule them to run sometime in the future without errors.

So those Twitter balloons you get on your birthday are most likely the work of cron jobs.

Please feel free to reach out to me on LinkedIn or Twitter. See you next time.

Till then, keep coding.

--

--