Cron-like jobs in NestJS

Liam Goring
2 min readAug 6, 2021

Want to schedule tasks in a way like Cron? NestJS has it baked right in!

So you want to be able to schedule a small task but only know how to use Cron? Well NestJS has you covered with their ScheduleModule built in module.

First we need to install the package to our project.

Next we need to add the module to the app.module to activate it. This makes it so any declared cron jobs are initialized and registered. As per the docs the registration occurs when the onApplicationBootstrap lifecycle hook occurs.

Next we want to create a service that will hold our cron jobs. Create a new file in a shared folder such as src/shared/<file-name> for our example we’ll call it scheduled-tasks.service.ts . Our service will contain one job that posts to the log every 45 seconds.

Finally we have to provide our newly created service to the app.module.ts file in the providers

And we’re done! We now have a Cron like job that will run every 45 seconds that will write to the log. This is extremely handy if you have a resource intensive job you’d like to schedule to run at certain times.

Now when you run your project you should see your log messages start to contain the message we defined in our scheduled-tasks.service.ts file.

There’s a few more ways to extend this functionality which you can check out here:

Thanks for reading!