To schedule CRON tasks in a Nest.js application, you can use the @nestjs/schedule
package, which provides decorators and utilities for scheduling jobs.
Here’s a step-by-step guide to setting up CRON tasks in Nest.js:
Step 1: Install the Required Packages
First, you need to install the @nestjs/schedule
package:
npm install --save @nestjs/schedule
Step 2: Create a CRON Job
Create a new service that will contain your CRON job logic. For example, create a file named cron.service.ts
:
In this example, handleCron
method will run every 30 minutes according to the CRON expression CronExpression.EVERY_30_MINUTES
.
Step 3: Register the CRON Module
Modify your module (app.module.ts
) to register the ScheduleModule
and your CronService
:
Step 4: Run your Nest.js Application
Start your Nest.js application:
npm run start
Now, your CRON job defined in CronService
will run according to the specified schedule.
Additional Tips:
- CRON Expressions: Use
CronExpression
constants (e.g.,CronExpression.EVERY_30_MINUTES
) for common schedules. You can also specify custom CRON expressions for more specific schedules. - Dependency Injection: You can inject other Nest.js services into your CRON service just like any other service.
- Testing CRON Jobs: Test your CRON jobs as you would test other parts of your Nest.js application. Consider mocking dependencies for unit testing.
By following these steps, you can easily schedule and run CRON jobs within your Nest.js application using the @nestjs/schedule
package.