In many web applications, we can see tasks are often triggered by users. Users press a button to execute a process if they need to perform that task again, they must manually initiate it each time. However, what if you want to automate certain tasks to run at specific times automatically without requiring user intervention?
Let’s consider an example from a fitness app. Suppose you own a gym, and your app offers members personalized workout routines. Every morning, you want to send a reminder notification at 6 AM with the day’s workout plan to each member. Manually sending these notifications every day would be time-consuming and prone to mistakes. You might forget one day, or accidentally send the wrong workout plan to the wrong member, causing confusion.
This is where Nestjs background jobs come in handy. With a background job, you could schedule this task to run automatically at the same time every day, ensuring that each member receives their notification without any manual effort. NestJS background jobs enable you to automate repetitive tasks based on time, and they don’t require any user input.
By utilizing NestJS, you can easily manage and schedule such jobs, allowing you to automate processes efficiently and accurately. This makes handling tasks like daily notifications, scheduled maintenance, or recurring updates a breeze.
So in this article, we are going to use NestJS cron jobs to schedule our tasks and see how they automate a simple process after a certain time or on a specific day and time.
Setup NestJs project
The first step is to create a project setup. Node and the NestJS CLI are already installed, and I created a basic NestJS project with the nest new
command, naming it NestJS Background Jobs
nest new cron-jobs
In the next phase, we are going to install the dependency for the cron job in Nest. Just copy this command line and paste it into your terminal.It will take some time.
npm install @nestjs/schedule
Create the Task Service
Now we are going to create a Service for this kind of automated task. We are going to name it Task Service, but in your real application, you can create a separate service with any name you choose and write code, such as sending push notifications. I have another detailed article on how to send push notifications in NestJS with Firebase.
In this Task Service, I will create a simple function and log a message to the console for demonstration purposes.
import { Injectable } from '@nestjs/common';
@Injectable()
export class TaskService {
sayHello() {
console.log('cron job');
}
}
In this Task Service, I will create a simple function and log a message to the console for demonstration purposes.
Add a Cron Decorator to Automate This Function
The Task Service function is not automated, as it will only be called when another controller or function invokes it. However, in our current scenario, we need to automate it to run every 5 seconds. To achieve this, we need to decorate this function with a cron job. we will add this @Cron(‘*/5 * * * * *’) and the above function will look like this.
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
@Injectable()
export class TaskService {
@Cron('*/5 * * * * *')
sayHello() {
console.log('cron job');
}
}
Now you might be wondering what these tasks are and how they work. Here is the explanation.
* * * * * *
| | | | | |
| | | | | Day of the week (1=Monday, 7=Sunday)
| | | | Month (1=January, 12=December)
| | | Day of the month (1-31)
| | Hour (0-23, where 0=midnight)
| Minute (0-59) of every hour
| Second (0-59) if given 1 it will run on first second of
Explanation
- Day of Week: Defines the day of the week (1=Monday, 7=Sunday).
Seconds: If you set this to1
, the job runs at the 1st second of every minute. - Minutes: If set to
1
, it runs at the 1st minute of every hour. - Hour: Represents the hour of the day (0-23). For example,
23
means 11 PM. - Day of Month: Runs on specific days of the month (1-31).
- Month: Indicates the month of the year (1-12).
Note:
For ranges, we can use -
and for steps, we can use /
.
Example:
* * * * * *
: Runs every second.0 * * * * *
: Runs at the start of every minute.0 0 * * * *
: Runs at midnight (00:00) every day.0 12 * * 5 *
: Runs at noon (12:00) every Friday.*/10 * * * * *
: Runs every 10 seconds. (Steps: Runs every 5 seconds.)0 9-17 * * * *
: Runs at the start of every hour from 9 AM to 5 PM. (Range: Hours 9 to 17.)
Quick Way to Schedule a Cron Job
It seems a bit difficult to schedule a job using *, /, –. The NestJS schedule library supports you by providing a cron expression enum to schedule jobs. For example, we can run a job every 5 seconds, as shown here.
import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
@Injectable()
export class TaskService {
@Cron(CronExpression.EVERY_5_SECONDS)
sayHello() {
console.log('cron job');
}
}
CronExpression Enum:
Here is the cron expression enum. you can use these values according to your requirements.
export enum CronExpression {
EVERY_SECOND = '* * * * * *',
EVERY_5_SECONDS = '*/5 * * * * *',
EVERY_10_SECONDS = '*/10 * * * * *',
EVERY_30_SECONDS = '*/30 * * * * *',
EVERY_MINUTE = '*/1 * * * *',
EVERY_5_MINUTES = '0 */5 * * * *',
EVERY_10_MINUTES = '0 */10 * * * *',
EVERY_30_MINUTES = '0 */30 * * * *',
EVERY_HOUR = '0 0-23/1 * * *',
EVERY_2_HOURS = '0 0-23/2 * * *',
EVERY_3_HOURS = '0 0-23/3 * * *',
EVERY_4_HOURS = '0 0-23/4 * * *',
EVERY_5_HOURS = '0 0-23/5 * * *',
EVERY_6_HOURS = '0 0-23/6 * * *',
EVERY_7_HOURS = '0 0-23/7 * * *',
EVERY_8_HOURS = '0 0-23/8 * * *',
EVERY_9_HOURS = '0 0-23/9 * * *',
EVERY_10_HOURS = '0 0-23/10 * * *',
EVERY_11_HOURS = '0 0-23/11 * * *',
EVERY_12_HOURS = '0 0-23/12 * * *',
EVERY_DAY_AT_1AM = '0 01 * * *',
EVERY_DAY_AT_2AM = '0 02 * * *',
EVERY_DAY_AT_3AM = '0 03 * * *',
EVERY_DAY_AT_4AM = '0 04 * * *',
EVERY_DAY_AT_5AM = '0 05 * * *',
EVERY_DAY_AT_6AM = '0 06 * * *',
EVERY_DAY_AT_7AM = '0 07 * * *',
EVERY_DAY_AT_8AM = '0 08 * * *',
EVERY_DAY_AT_9AM = '0 09 * * *',
EVERY_DAY_AT_10AM = '0 10 * * *',
EVERY_DAY_AT_11AM = '0 11 * * *',
EVERY_DAY_AT_NOON = '0 12 * * *',
EVERY_DAY_AT_1PM = '0 13 * * *',
EVERY_DAY_AT_2PM = '0 14 * * *',
EVERY_DAY_AT_3PM = '0 15 * * *',
EVERY_DAY_AT_4PM = '0 16 * * *',
EVERY_DAY_AT_5PM = '0 17 * * *',
EVERY_DAY_AT_6PM = '0 18 * * *',
EVERY_DAY_AT_7PM = '0 19 * * *',
EVERY_DAY_AT_8PM = '0 20 * * *',
EVERY_DAY_AT_9PM = '0 21 * * *',
EVERY_DAY_AT_10PM = '0 22 * * *',
EVERY_DAY_AT_11PM = '0 23 * * *',
EVERY_DAY_AT_MIDNIGHT = '0 0 * * *',
EVERY_WEEK = '0 0 * * 0',
EVERY_WEEKDAY = '0 0 * * 1-5',
EVERY_WEEKEND = '0 0 * * 6,0',
EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT = '0 0 1 * *',
EVERY_1ST_DAY_OF_MONTH_AT_NOON = '0 12 1 * *',
EVERY_2ND_HOUR = '0 */2 * * *',
EVERY_2ND_HOUR_FROM_1AM_THROUGH_11PM = '0 1-23/2 * * *',
EVERY_2ND_MONTH = '0 0 1 */2 *',
EVERY_QUARTER = '0 0 1 */3 *',
EVERY_6_MONTHS = '0 0 1 */6 *',
EVERY_YEAR = '0 0 1 1 *',
EVERY_30_MINUTES_BETWEEN_9AM_AND_5PM = '0 */30 9-17 * * *',
EVERY_30_MINUTES_BETWEEN_9AM_AND_6PM = '0 */30 9-18 * * *',
EVERY_30_MINUTES_BETWEEN_10AM_AND_7PM = '0 */30 10-19 * * *',
MONDAY_TO_FRIDAY_AT_1AM = '0 0 01 * * 1-5',
MONDAY_TO_FRIDAY_AT_2AM = '0 0 02 * * 1-5',
MONDAY_TO_FRIDAY_AT_3AM = '0 0 03 * * 1-5',
MONDAY_TO_FRIDAY_AT_4AM = '0 0 04 * * 1-5',
MONDAY_TO_FRIDAY_AT_5AM = '0 0 05 * * 1-5',
MONDAY_TO_FRIDAY_AT_6AM = '0 0 06 * * 1-5',
MONDAY_TO_FRIDAY_AT_7AM = '0 0 07 * * 1-5',
MONDAY_TO_FRIDAY_AT_8AM = '0 0 08 * * 1-5',
MONDAY_TO_FRIDAY_AT_9AM = '0 0 09 * * 1-5',
MONDAY_TO_FRIDAY_AT_09_30AM = '0 30 09 * * 1-5',
MONDAY_TO_FRIDAY_AT_10AM = '0 0 10 * * 1-5',
MONDAY_TO_FRIDAY_AT_11AM = '0 0 11 * * 1-5',
MONDAY_TO_FRIDAY_AT_11_30AM = '0 30 11 * * 1-5',
MONDAY_TO_FRIDAY_AT_12PM = '0 0 12 * * 1-5',
MONDAY_TO_FRIDAY_AT_1PM = '0 0 13 * * 1-5',
MONDAY_TO_FRIDAY_AT_2PM = '0 0 14 * * 1-5',
MONDAY_TO_FRIDAY_AT_3PM = '0 0 15 * * 1-5',
MONDAY_TO_FRIDAY_AT_4PM = '0 0 16 * * 1-5',
MONDAY_TO_FRIDAY_AT_5PM = '0 0 17 * * 1-5',
MONDAY_TO_FRIDAY_AT_6PM = '0 0 18 * * 1-5',
MONDAY_TO_FRIDAY_AT_7PM = '0 0 19 * * 1-5',
MONDAY_TO_FRIDAY_AT_8PM = '0 0 20 * * 1-5',
MONDAY_TO_FRIDAY_AT_9PM = '0 0 21 * * 1-5',
MONDAY_TO_FRIDAY_AT_10PM = '0 0 22 * * 1-5',
MONDAY_TO_FRIDAY_AT_11PM = '0 0 23 * * 1-5',
}
Conclusion
In this article, we explored the power of NestJS background jobs, specifically focusing on how to utilize cron jobs to automate repetitive tasks in web applications. By automating tasks such as sending daily notifications, you not only save valuable time but also reduce the risk of human error, ensuring that your users receive consistent and accurate information.
We demonstrated the setup of a NestJS project, the installation of necessary dependencies, and the creation of a Task Service equipped with a simple cron job. This process highlighted the ease with which you can schedule tasks to run at specific intervals without manual intervention. With features like cron expression enums, managing these automated tasks becomes even more straightforward.
Whether you need to send notifications, perform regular maintenance, or handle any recurring operations, leveraging NestJS’s scheduling capabilities allows you to streamline your processes and improve the user experience. Embrace the efficiency of automation and enhance your application’s functionality with NestJS background jobs.
FAQ Section
1. What are NestJS background jobs?
NestJS background jobs are automated tasks that can run at specific times or intervals without requiring user intervention. They help streamline processes such as sending notifications or performing regular maintenance tasks.
2. How do cron jobs work in NestJS?
Cron jobs in NestJS use cron expressions to define when a task should be executed. These expressions allow you to schedule tasks based on time intervals (e.g., every minute, every hour, etc.) using a simple syntax.
3. Why should I use cron jobs for my application?
Using cron jobs can save time and reduce human error by automating repetitive tasks. This ensures that important processes, such as sending notifications or updates, occur consistently and accurately without manual effort.
4. How do I set up a cron job in NestJS?
To set up a cron job in NestJS, you first create a Task Service and decorate a function with the @Cron
decorator. You can use cron expressions to specify how often the task should run, such as @Cron('*/5 * * * * *')
for every 5 seconds.
5. What is a cron expression, and how is it structured?
A cron expression is a string that defines the schedule for executing a cron job. It consists of six fields: seconds, minutes, hours, day of the month, month, and day of the week. Each field can include specific values, ranges, or intervals.
6. Can I use predefined cron expressions in NestJS?
Yes, NestJS provides predefined cron expression enums through the CronExpression
class, making it easier to schedule jobs without needing to remember the syntax. For example, @Cron(CronExpression.EVERY_5_SECONDS)
runs a job every 5 seconds.
7. Are there any limitations to using cron jobs in NestJS?
While cron jobs are powerful, they may not be suitable for every scenario. For long-running tasks or processes requiring significant resources, consider other solutions such as message queues or background job processing libraries.
8. How can I monitor or manage cron jobs in my NestJS application?
You can implement logging or monitoring solutions within your Task Service to track job executions and handle errors. Additionally, consider using tools like Bull or Agenda for more advanced job management and monitoring capabilities.
Leave a Reply