VitNode

Cron Jobs

Task Scheduling (CRON) in VitNode.

We're using @nestjs/schedule to schedule tasks. CRON is a time-based job scheduler in Unix-like operating systems. It enables users to schedule jobs (commands or scripts) to run periodically at fixed times, dates, or intervals.

Usage

Create a service for cron jobs.

clear.cron.ts
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule'; 
 
@Injectable()
export class ClearCoreMembersCron {

  @Cron('45 * * * * *', {

    name: 'ExampleCron',

  })
  exampleCron() {
    console.log('Called when the current second is 45');
  }
}

Register the service in your module providers array.

members.module.ts
import { Module } from '@nestjs/common';
 
import { ClearCoreMembersCron } from './clear.cron'; 
 
@Module({
  providers: [ClearCoreMembersCron], 
})
export class CoreMembersModule {}

CRON Expression

The @Cron() decorator supports the following standard cron patterns:

Asterisk (e.g. *) Ranges (e.g. 1-3,5) Steps (e.g. */2)

* * * * * *
| | | | | |
| | | | | day of week
| | | | months
| | | day of month
| | hours
| minutes
seconds (optional)

Or you can use a CronExpression enum.

clear.cron.ts
import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule'; 
 
@Injectable()
export class ClearCoreMembersCron {

  @Cron(CronExpression.EVERY_30_SECONDS, {
    name: 'ExampleCron',
  })
  exampleCron() {
    console.log('Called every 30 seconds');
  }
}

On this page