DEV Community

Cover image for How to schedule a cron job with NestJs in less than 5 mins
Edgar Gonzalez
Edgar Gonzalez

Posted on

How to schedule a cron job with NestJs in less than 5 mins

Yes, I know you can setup a cron job directly with Linux, or with plain node libraries, but, in my case coming from and angular background developing with NestJs made things much simpler, also, I think it is really fun trying new approaches just for the sake of it. Taking that into account let's continue.

Creating cron this way is not at OS level, it will only be at app level, so if your app stops the cron won't execute anymore.

This is particularly useful when you don't have access to change or set OS level configurations.

A couple of days ago I was in the need of developing a very simple app, that fetched some information from an API every minute and posted the results in a Slack channel (you can read about the slack part over here). I have developed a couple of apps with NestJs in the past and wanted to give it a try this time.

The first thing you need to do is to install NestJs cli (if you haven't already), with the following command:

npm i -g @nestjs/cli

You can also use npx if you don't want to install the cli globally.

After that you can create your project with this command:

nest new project-name

There is already a built-in Scheduler module inside NestJs we can use, and it uses node-cron package internally, you can install it with the following command:

npm install --save @nestjs/schedule

Once you have installed the package add it to the app.module like this:

import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';

@Module({
  imports: [
    ScheduleModule.forRoot()
  ],
  ...
})
export class AppModule {}

Now, you need to create a service and provide it in your app.module as well, that will be as simple as running the following command:

nest generate service cron

Now that you have the service ready let me explain some types of crons you can create with the Schedule module.

  1. Custom cron expressions, something similar to 10 * * * *, that will run your cron every 10 minutes or 0 20 * * *, that will run your cron every day at 8:00 PM. You can read more about cron expressions here.
  2. Predefined expressions from the CronExpression enum, something like CronExpression.EVERY_MINUTE or CronExpression.EVERY_2_HOURS, this enum contains common human-readable cron expressions you can use.
  3. Crons that runs only once after X milliseconds, something like run 5 minutes after the app started.

Custom cron expressions

To set custom cron expressions, you need to use the @Cron decorator over the method that will be executed:

@Cron('*/10 * * * * *')
runEvery10Seconds() {
 console.log('Every 10 seconds');
}

Predefined cron expressions

To use predefined expressions you also need to use the @Cron decorator, but instead of writing the expression yourself you will take it from the CronExpresion enum:

@Cron(CronExpression.EVERY_MINUTE)
runEveryMinute() {
 console.log('Every minute');
}

You can find all Predefined expressions here.

Run once after x milliseconds

If you ever come to a scenario that you need to execute a method some time after your app started, and only once, you can use the @Timeout decorator like this:

@Timeout(15000)
onceAfter15Seconds() {
 console.log('Called once after 15 seconds');
}

Once you run npm run start:dev, you will see something similar to this in your terminal:

Every 10 seconds
Called once after 15 seconds
Every 10 seconds
Every 10 seconds
Every 10 seconds
Every 10 seconds
Every minute
Every 10 seconds

Those are all the types I will cover on this post, there are other cool functionalities for creating cron jobs dynamically using Schedule modules API. You can take a deeper look here.

You can find the source code for this example here. See you the next time.

And if you are interested on how to dockerize your NestJs app, you can check this article.

Top comments (2)

Collapse
 
igorissen profile image
Ismael Gorissen

Is it mandatory to use a server to launch CRON jobs?

Collapse
 
colonelpopcorn profile image
Jonathan Ling

It does allow people to deploy cron jobs to a PaaS that they don't have underlying OS access to. Think Heroku or ElasticBeanstalk.