Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nestjs-schedule

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nestjs-schedule

nestjs distributed timer schedule lib

  • 0.1.8
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
717
increased by37.62%
Maintainers
1
Weekly downloads
 
Created
Source

Nest Logo

Nestjs Schedule

NPM Version Package License NPM Downloads

Description

Distributed Schedule module for Nest.js based on the node-schedule package.

Installation

$ npm i --save nestjs-schedule

Usage

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

@Module({
    imports: [ScheduleModule.forRoot({
        // Optional: Import external dependent modules if you need
        imports: [MyLockerModule]
        // Optional: Inject your global custom lock
        useClass: MyScheduleLocker
    })],
})
export class AppModule {}
import { Injectable, Logger } from '@nestjs/common';
import { Cron, Timeout, Interval } from 'nestjs-schedule';

@Injectable()
export class TasksService {
    private readonly logger = new Logger(TasksService.name);

    @Cron('45 * * * * *')
    handleCron() {
        this.logger.debug('Called when the current second is 45');
    }

    @Interval(5000)
    handleInterval() {
        this.logger.debug('Called every 5 seconds');
    }

    @Timeout(5000)
    handleTimeout() {
        this.logger.debug('Called after 5 seconds');
    }
}

Dynamic Schedule Job

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { InjectSchedule, Schedule } from 'nestjs-schedule';

@Injectable()
export class TasksService implements OnModuleInit {
    private readonly logger = new Logger(TasksService.name);

    constructor(@InjectSchedule() private readonly schedule: Schedule) {}

    execute() {
        this.logger.debug('execute dynamic job');
    }

    onModuleInit() {
        this.schedule.createIntervalJob(this.execute.bind(this), 3000, {
            name: 'test_job',
        });
        this.schedule.deleteIntervalJob('test_job');
    }
}

Distributed Support

  1. Implements Locker interface
import { Locker } from 'nestjs-schedule';
import { Injectable } from '@nestjs/common';

@Injectable()
export class ScheduleLocker implements Locker {

    release(jobName: string): any {}

    async tryLock(jobName: string): Promise<boolean> {
        // use redis lock or other methods
        return true;
    }
}
  1. Use your locker
import { Injectable, Logger } from '@nestjs/common';
import { Cron, UseLocker } from '@nestjs-schedule';
import { ScheduleLocker } from './schedule-locker';

@Injectable()
export class TasksService {
    private readonly logger = new Logger(TasksService.name);

    @Cron('45 * * * * *')
    // remove it if you want to use the lock which injected forRoot
    @UseLocker(ScheduleLocker)
    handleCron() {
        this.logger.debug('Called when the current second is 45');
    }
}

API

class ScheduleModule

static forRoot(): DynamicModule

Import schedule module.

class Schedule

createTimeoutJob(methodRef: Function, timeout: number, options?: TimeoutOptions)

Dynamic create a timeout job.

fieldtyperequireddescription
methodRefFunctiontruejob method
timeoutnumbertruemilliseconds
optionsfalsesee decorators
lockerLocker/falsefalsecustom lock instance

If the locker is configured as false, the default lock will be ignored

createIntervalJob(methodRef: Function, timeout: number, options?: IntervalOptions)

Dynamic create a interval job.

fieldtyperequireddescription
methodRefFunctiontruejob method
intervalnumbertruemilliseconds
optionsfalsesee decorators
lockerLocker/falsefalsecustom lock instance
createCronJob(rule: string | number | Date | CronObject | CronObjLiteral, methodRef, options?: CronOptions)

Dynamic create a cron job.

fieldtyperequireddescription
ruleDate string number CronObject CronObjLiteraltruethe cron rule
methodRefFunctiontruejob method
optionsfalsesee decorators
lockerLocker/falsefalsecustom lock instance
deleteTimeoutJob(name: string)

Delete a timeout job

deleteIntervalJob(name: string)

Delete a interval job

deleteCronJob(name: string)

Delete a cron job

getTimeoutJobs(): TimeoutJobOptions[]

Get all timeout jobs

getIntervalJobs(): IntervalJobOptions[]

Get all interval jobs

getCronJobs(): CronJobOptions[]

Get all cron jobs

Decorators

Cron(rule: string | number | Date | CronObject | CronObjLiteral, options?: CronOptions): MethodDecorator

Schedule a cron job.

fieldtyperequireddescription
ruleDate string number CronObject CronObjLiteraltrueThe cron rule
rule.dayOfWeeknumbertrueTimezone
options.namestringfalseThe unique job key.Distributed lock need it
options.retriesnumberfalsethe max retry count, default is -1 not retry
options.retrynumberfalsethe retry interval, default is 5000

CronObject CronObjLiteral

Interval(timeout: number): MethodDecorator

Interval(name: string, timeout: number): MethodDecorator

Interval(name: string, timeout: number, options?: IntervalOptions): MethodDecorator

Schedule a interval job.

fieldtyperequireddescription
timeoutnumbertruemilliseconds
options.retriesnumberfalsethe max retry count, default is -1 not retry
options.retrynumberfalsethe retry interval, default is 5000
options.immediatebooleanfalseexecuting job immediately

Timeout(timeout: number): MethodDecorator

Timeout(name: string, timeout: number): MethodDecorator

Timeout(name: string, timeout: number, options?: TimeoutOptions): MethodDecorator

Schedule a timeout job.

fieldtyperequireddescription
timeoutnumbertruemilliseconds
options.retriesnumberfalsethe max retry count, default is -1 not retry
options.retrynumberfalsethe retry interval, default is 5000
options.immediatebooleanfalseexecuting job immediately

InjectSchedule(): PropertyDecorator

Inject Schedule instance

UseLocker(locker: Locker | Function): MethodDecorator

Set a distributed locker for job.

Stay in touch

License

NestCloud is MIT licensed.

Keywords

FAQs

Package last updated on 24 May 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc