Code Monkey home page Code Monkey logo

schedule's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads Coverage Discord Backers on Open Collective Sponsors on Open Collective

Description

Schedule module for Nest based on the cron package.

Installation

$ npm install --save @nestjs/schedule

Quick Start

Overview & Tutorial

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.

schedule's People

Contributors

amokio avatar bangbang93 avatar borales avatar caucik avatar cavanmflynn avatar d-lukutin avatar dependabot[bot] avatar jeffminsungkim avatar johnbiundo avatar jozsefsallai avatar kamilmysliwiec avatar micalevisk avatar nergie avatar nosfistis avatar origranot avatar pyassine avatar renovate-bot avatar renovate[bot] avatar sheerlox avatar tony133 avatar willyjchen avatar wodcz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

schedule's Issues

0.4.2 Exception is not readble

I'm submitting a...


[ ] Regression 
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

0|server | [Nest] 2026877 - 01/25/2021, 12:00:00 PM [Scheduler] Object:
0|server | {}
0|server | +10ms

Expected behavior

the error object or error message

Minimal reproduction of the problem with instructions

just throw error inside scheduled function

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
    "@nestjs/common": "^7.6.5",
    "@nestjs/config": "^0.6.2",
    "@nestjs/core": "^7.6.5",
    "@nestjs/jwt": "^7.2.0",
    "@nestjs/passport": "^7.1.5",
    "@nestjs/platform-express": "^7.6.5",
    "@nestjs/schedule": "0.4.2"


For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Cannot find module '@nestjs/schedule' or its corresponding type declarations.

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

[8/9] RUN nest build:
#12 17.86 src/app.module.ts:4:32 - error TS2307: Cannot find module '@nestjs/schedule' or its corresponding type declarations.
#12 17.86
#12 17.86 4 import { ScheduleModule } from '@nestjs/schedule';
#12 17.86 ~~~~~~~~~~~~~~~~~~
#12 17.86 src/app.service.ts:2:26 - error TS2307: Cannot find module '@nestjs/schedule' or its corresponding type declarations.
#12 17.86
#12 17.86 2 import { Interval } from '@nestjs/schedule';
#12 17.86 ~~~~~~~~~~~~~~~~~~
#12 17.86
#12 17.87 Found 2 error(s).
#12 17.87

Minimum reproduction code

https://github.com/nestjs/schedule.git

Steps to reproduce

NODE_VERSION=16.14.0
APP_NAME=nestjs-api
APP_VERSION=0.0.7-rc.0
NODE_ENV=production
APP_PORT=3000

version: '3.8'

services:
node:
container_name: ${APP_NAME}
image: ${APP_NAME}:${APP_VERSION}
build:
context: .
dockerfile: Dockerfile.dev
command: npm run start:prod
ports:
- 3000:3000
restart: unless-stopped

FROM node:16.14.0

WORKDIR /usr/src/app

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

COPY . /usr/src/app/

RUN npm config set loglevel http

npm install glob

RUN npm install @nestjs/cli -g

npm install dependency

RUN npm install

RUN npm run build

COPY . .

CMD ["node", "dist/main"]

Expected behavior

src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { ScheduleModule } from '@nestjs/schedule';

@module({
// imports: [ScheduleModule.forRoot()],
imports: [ScheduleModule.forRoot()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

app.service.ts

import { Injectable } from '@nestjs/common';
import { Interval } from '@nestjs/schedule';
// import { Cron, CronExpression } from '@nestjs/schedule';

@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}

// @Cron(CronExpression.EVERY_30_SECONDS)
@interval(10000)
handleCron() {
console.log('Test');
}
}

Package version

8.1.3

NestJS version

No response

Node.js version

No response

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

@Cron decorator throws: TypeError: cron_1.CronJob is not a constructor

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

By following the example here: https://docs.nestjs.com/techniques/task-scheduling I have code that looks like that:

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

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

But I get the following error

(node:20320) UnhandledPromiseRejectionWarning: TypeError: cron_1.CronJob is not a constructor
    at ...\node_modules\@nestjs\schedule\dist\scheduler.orchestrator.js:58:29

Expected behavior

No error should be thrown. In fact if I use @Interval instead of @Cron it works as expected:

 @Interval(1000)
  handleCron() {
    this.logger.debug('Called when the current second is 45');
  }
[Nest] 23620   - 2020-01-03 14:35:18   [TestCron] Called when the current second is 45
[Nest] 23620   - 2020-01-03 14:35:19   [TestCron] Called when the current second is 45
[Nest] 23620   - 2020-01-03 14:35:20   [TestCron] Called when the current second is 45

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


    "@nestjs/common": "^6.10.13",
    "@nestjs/config": "0.0.7",
    "@nestjs/core": "^6.10.13",
    "@nestjs/schedule": "^0.1.1",

Feature request: add runOnInit options in Cron decorator

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Cannot set runOnInit by Cron decorator
https://github.com/nestjs/schedule/blob/master/lib/decorators/cron.decorator.ts#L22

Expected behavior

Can set runOnInit by Cron decorator.
I think you can use runOnInit options instead of starting cron on application bootstrap
https://github.com/nestjs/schedule/blob/master/lib/scheduler.orchestrator.ts#L81

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

You can decide to run a cron at startup or not. I know you can use "Dynamic Cron jobs" but I think using decorators is a better way.

Environment


Nest version: 7.4.2

 
For Tooling issues:
- Node version: 12  
- Platform:  Windows 

Others:

Cron type error when building in strict mode

I'm submitting a...


[ ] Regression 
[x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When trying to build a project that uses @nestjs/schedule (either by running yarn build, nest build or yarn run tsc --build) and has strict: true set in tsconfig.json, a Typescript error halts the process:

node_modules/@nestjs/schedule/dist/scheduler.registry.d.ts:1:25 - error TS7016: Could not find a declaration file for module 'cron'. '/Users/roberto/Dev/nest/scheduler-bug/node_modules/cron/lib/cron.js' implicitly has an 'any' type.
  Try `npm install @types/cron` if it exists or add a new declaration (.d.ts) file containing `declare module 'cron';`

1 import { CronJob } from 'cron';
                          ~~~~~~

Found 1 error(s).

Expected behavior

Build should be able to finish without errors. A workaround is manually installing @types/cron, but as the user of the library I don't expect to install additional dependencies. A probable fix is to add @types/cron to the project dependencies (right now it is a dev dependency).

Minimal reproduction of the problem with instructions

Minimal reproduction repo

Just clone it and run yarn && yarn build.

What is the motivation / use case for changing the behavior?

Environment


Nest version: 7.0.7

 
For Tooling issues:
- Node version: v12.16.1
- Platform:  Mac

Others:

Feature request: Add runOnInit in CronOptions interface

I'm submitting a Feature request.

What do you think about adding in interface CronOptions variable runOnInit for CronJob constructor?

For locale or integration environment I need to start Job every initialization. For the production environment only in CronTime time.

Thank you for your work. You do a great job.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

getCronJob problem

I'm submitting a problem with getCronJob


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Code:
-create crone

  addCronJob(
    tokens: string[],
    name: string,
    day: string,
    hours: string,
    seconds: string,
    type: NotificationType,
  ): void {
    const job = new CronJob(`${seconds} * * * * *`, async () => {
      this.logger.log(`time (${seconds}) for job ${name} to run!`);

      switch (type) {
        case 'push':
          this.messageService.sendMessage(tokens);
          break;
        case 'email':
          console.log('sendEmail');
          break;
      }
    });

    this.scheduler.addCronJob(name, job);
    job.start();

    this.logger.log(`job ${name} added for each minute at ${seconds} seconds!`);
  }

-get all crone jobs(working fine) and get specific crone job(not working)

      const jobs = this.scheduler.getCronJobs();`
      jobs.forEach((value, key, map) => {
      let next;
      try {
        next = value.nextDates().toDate();
      } catch (e) {
        next = 'error: next fire date is in the past!';
      }
      this.logger.log(`job: ${key} -> next: ${next}`);
      });

      const { category } = notification;
      const job = this.scheduler.getCronJob(category);

Logs:
[Nest] 36959 - 12/19/2020, 2:59:28 PM [NotificationService] job: 5fdcb3c9a605c86ed37eaec9 -> next: Sat Dec 19 2020 15:00:05 GMT+0100 (Central European Standard Time)

[Nest] 36959 - 12/19/2020, 2:59:28 PM [NotificationService] job: 5fdcb3b0a605c86ed37eaec7 -> next: Sat Dec 19 2020 15:00:07 GMT+0100 (Central European Standard Time)

[Nest] 36959 - 12/19/2020, 2:59:28 PM [NotificationService] job: 5fdca82d0c17a46d7b79c6a5 -> next: Sat Dec 19 2020 15:00:08 GMT+0100 (Central European Standard Time)

[Nest] 36959 - 12/19/2020, 2:59:28 PM [ExceptionsHandler] No Cron Job was found with the given name (5fdca82d0c17a46d7b79c6a5). Check that you created one with a decorator or with the create API. +4ms Error: No Cron Job was found with the given name (5fdca82d0c17a46d7b79c6a5). Check that you created one with a decorator or with the create API. at SchedulerRegistry.getCronJob (/Users/mateuszstepien/Documents/instasmile-backend/node_modules/@nestjs/schedule/dist/scheduler.registry.js:20:19) at NotificationService.delete (/Users/mateuszstepien/Documents/instasmile-backend/dist/notification/notification.service.js:85:36) at processTicksAndRejections (internal/process/task_queues.js:97:5) at async /Users/mateuszstepien/Documents/instasmile-backend/node_modules/@nestjs/core/router/router-execution-context.js:46:28 at async /Users/mateuszstepien/Documents/instasmile-backend/node_modules/@nestjs/core/router/router-proxy.js:9:17

Crone with given name(5fdca82d0c17a46d7b79c6a5) exist but throw error...

Expected behavior

getCroneJob should find a job for given name.

Environment


Nest version: 7.4.1

 
For Tooling issues:
- Node version: v12.18.3
- Platform: Mac

feat: use cron name to log error

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Improve unhandled exceptions inside cron tasks.

Describe the solution you'd like

Use cron name if provided as context for log.error message.

Update:

this.logger.error(error);

from: this.logger.error(error)

to: this.logger.error(error, cronName)

cronName would be add as param for wrapFunctionInTryCatchBlocks existing method, it can be null if so, use Scheduler as default

Teachability, documentation, adoption, migration strategy

Not sure about add any tip about this in doc.

What is the motivation / use case for changing the behavior?

Currently when unexpected errors happens only error message is print without much context about where it came from, in big repos with many cron jobs it's hard to find which method thrown the error.

I'm able to implement this PR and understand that it can be considered unnecessary as exceptions should be handled inside each cron.

image

ChainAlert: npm package release (2.0.0) has no matching tag in this repo

Dear @nestjs/schedule maintainers,
Thank you for your contribution to the open-source community.

This issue was automatically created to inform you a new version (2.0.0) of @nestjs/schedule was published without a matching tag in this repo.

As part of our efforts to fight software supply chain attacks, we would like to verify this release is known and intended, and not a result of an unauthorized activity.

If you find this behavior legitimate, kindly close and ignore this issue. Read more

badge

Circular dependency error while just importing ScheduleModule inside AppModule

I'm submitting a...


[ ] Regression 
[ x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When trying to import the ScheduleModule, then I receive a circular dependency error while server is initializing

Error: Nest cannot create the module instance. Often, this is because of a circular dependency between modules. Use forwardRef() to avoid it. 
(Read more: https://docs.nestjs.com/fundamentals/circular-dependency)
Scope [AppModule -> ]

Expected behavior

Importing the ScheduleModule shouldn't produce a circular dependency problem

Minimal reproduction of the problem with instructions

@Module({
  imports: [
    HttpModule,
    TypeOrmModule.forRoot({
      aConfig
    }),
    CacheModule.register(),
    SomeMoreModulesOfMyOwn,
    ScheduleModule.forRoot()
  ],
  controllers: [
    AppController
  ]
})
export class AppModule implements NestModule {
  constructor() {
  }

  configure(consumer: MiddlewareConsumer) {
    if (process.env.log_requests === 'true') {
      consumer
        .apply(LoggerMiddleware)
        .forRoutes({ path: '*', method: RequestMethod.ALL });
    }
  }
}

What is the motivation / use case for changing the behavior?

fix a bug

Environment


Nest version: 6.10.5

 
For Tooling issues:
- Node version: 10.16.3  
- Platform:  Mac

Others:

Feature request: options to start cronjob on application bootstrap or not

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Always start the cronjob on application bootstrap
https://github.com/nestjs/schedule/blob/master/lib/scheduler.orchestrator.ts#L81

Expected behavior

There is an options to start the cronjob on application bootstrap or not

if(options.runOnApplicationBootstrap) {
  cronJob.start();
}

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

In my project, I have used "Dynamic API" to start a cronjob when an env is enabled. However, there are more cronjob, more code in onApplicationBoostrap function. Therefore, using a condition in Cron decorator is a fancy way to solve this problem.

Environment


Nest version: 7.4.2

 
For Tooling issues:
- Node version: 12  
- Platform:  Windows 

Others:

node-cron lib seems like not being maintained

Nest provides the @nestjs/schedule package, which integrates with the popular Node.js node-cron package. We'll cover this package in the current chapter.

The nestjs scheduling feature makes use of node-cron under the hood and the libs seems like not being maintained. 7 months without updates and a lot of repeated issues: kelektiv/node-cron#548, kelektiv/node-cron#547, kelektiv/node-cron#545, kelektiv/node-cron#542, kelektiv/node-cron#539 and a lot more. The issues have no comments.

This could represent a problem during the use of scheduling feature of nestjs since it relies too much on this lib? The fact that the lib is popular doesn't mean it should be used anymore.

Handling guards on CRON

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

I have an issue when I have multiple replicas of the Nest app and I want to run CRON jobs only on one of them. I do not want to create additional not replicated services. I do not want to create if in each function because that's what guards are for.

Describe the solution you'd like

I have two ideas:

  1. Preventing CRON registration by guards alongside with @Cron decorator.
    • Or add a guard as CRON decorator's argument or sth 🐱
  2. Preventing each CRON execution by running guard onTick (better solution)

Teachability, documentation, adoption, migration strategy

Non-breaking

What is the motivation / use case for changing the behavior?

I've got multiple jobs that have to be run only once but I still want to use a single Nest app with multiple replicas.

I could try to make a PR if that's ok.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

circleci
.circleci/config.yml
  • cimg/node 21.6
  • cimg/node 21.6
npm
package.json
  • cron 3.1.6
  • uuid 9.0.1
  • @commitlint/cli 19.2.1
  • @commitlint/config-angular 19.1.0
  • @nestjs/common 10.3.5
  • @nestjs/core 10.3.5
  • @nestjs/platform-express 10.3.5
  • @nestjs/testing 10.3.5
  • @types/jest 29.5.12
  • @types/node 20.11.30
  • @types/sinon 17.0.3
  • @types/uuid 9.0.8
  • @typescript-eslint/eslint-plugin 7.3.1
  • @typescript-eslint/parser 7.3.1
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • husky 9.0.11
  • jest 29.7.0
  • lint-staged 15.2.2
  • prettier 3.2.5
  • reflect-metadata 0.2.1
  • release-it 17.1.1
  • rimraf 5.0.5
  • rxjs 7.8.1
  • sinon 17.0.1
  • ts-jest 29.1.2
  • typescript 5.4.3
  • @nestjs/common ^8.0.0 || ^9.0.0 || ^10.0.0
  • @nestjs/core ^8.0.0 || ^9.0.0 || ^10.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

use `node-cron` instead `cron`

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

current depends on cron

Expected behavior

remove cron, use node-cron instead.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

I just take a short inspect on node-cron and cron. I think node-cron have a higher quality. also cron depends on moment timezone. but in cron project the dependence is luxon.

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Missing available options in documentation

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

What is the motivation / use case for changing the behavior?

I was looking to have my cron jobs running at a specific timezone. I did looked in the doc and didn't found anything. I had to dig into the source code to find it (

timeZone?: string;
). Maybe, you should add the available options into the nestjs documentation :)

Thanks,

Schedule tasks x timeunits after previous task has finished

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

From my understanding of the docs, there are currently three styles of scheduling supported: cron, interval and timeout-once.
None of them are what I would like to do, which is...

Expected behavior

...interval after last task finished. Essentially something like "run a new task 10 seconds after the previous task has finished".

What is the motivation / use case for changing the behavior?

For example, I have a task that should regularly poll something, let's say every ten seconds.
In these ten seconds, there could be very few or a lot of new things that I'm polling. If there are lots of new things that I need to process, this might take longer than the specified timeout. Ideally, I'd like to prevent my task from starting while the previous task is still running.

Multi core running app duplicate schedules saved with the same name

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Using PM2 with the option -i the app runs a multi multi thread, but when schedule is created at differents moments at a node running app under multi core, some schedule is created twice and more.

Expected behavior

Use redis, like @nestjs/websockets do, to save/create schedules

Cronjobs getting called multiple times

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I am using NestJs and trying to use the schedule module for cronjobs. One of the methods is decorated with @Cron('*/30 * * * * * ') and I expected it to run only once after 30 seconds. The issue is after every 30 seconds, the cron runs three times. This is a consistent behavior and happens all the time. However I have observed that other methods which are also cronjobs are working as expected(run only once). Have been trying to figure out the root cause but there is no luck so far.

Expected behavior

The cronjobs should always only run only once.

Minimal reproduction of the problem with instructions

@Cron('*/10 * *  * * *')
  async triggerSessionRemindersCron(): Promise<void> {
    LoggerService.logger.info(`Date:: ${new Date().getTime()}`);
    LoggerService.logger.info('CronjobService::triggerSessionReminders BEGIN');
    // await this.triggerEventsForSessionReminders().catch((e) => {
    //   LoggerService.logger.error(e);
    // });
  }

What is the motivation / use case for changing the behavior?

The current implementation for me results in sending multiple events to webengage which in turn sends multiple notifications to the users.

Environment


Nest version: 7.5.4

 
For Tooling issues:
- Node version: 12.18.2 -->
- Platform:   Mac

Others:
Using npm version 6.14.5

Add Support/Workaround to Scope.REQUEST Injected Service (ScheduledService not working)

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Scheduled Tasks not running when injected or nested service has @Injectable({ scope: Scope.REQUEST })

Expected behavior

Scheduled Tasks running normally.

Minimal reproduction of the problem with instructions

Step 1: Create a Service with:

@Injectable({ scope: Scope.REQUEST })
export class SomeService {}

Step 2: Inject SomeService into the Scheduled Service:

@Injectable()
export class ScheduledService {
  constructor(
    private readonly someService: SomeService,
  ) {
  }
}

What is the motivation / use case for changing the behavior?

If a service with Scope.REQUEST is not supported OK, but that should not stop Scheduled Services to work.

Environment


Nest version: 7.6.15

    "@nestjs/common": "7.6.15",
    "@nestjs/core": "7.6.15",
    "@nestjs/jwt": "7.2.0",
    "@nestjs/passport": "7.1.5",
    "@nestjs/platform-express": "7.6.15",
    "@nestjs/platform-socket.io": "7.6.15",
    "@nestjs/schedule": "0.4.3",
    "@nestjs/websockets": "7.6.15",
 
For Tooling issues:
- Node version: v12.20.0  
- Platform:  Mac 11.2.1 (20D74) 

Others:
Using Yarn.

Dynamic jobs not being cleared on application shutdown

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Any job created with SchedulerRegistry is not being cleared on application shutdown.

Expected behavior

All jobs, both those declared with decorators, and those declared with the Dynamic API, should be cleared on shutdown.

Minimal reproduction of the problem with instructions

You can run the test added below:
https://github.com/Nosfistis/schedule/tree/bugfix/shutdown-cleanup

As a quickfix to pass the test, add this to orchestrator:

  clearIntervals() {
    this.schedulerRegistry.getIntervals().forEach(interval => this.schedulerRegistry.deleteInterval(interval));
  }

What is the motivation / use case for changing the behavior?

This is an important issue since the application never really shuts down if closed with app.close(), and the jobs keep running. It has been a major issue in my e2e tests, and took a while to find out.

I am not sure why both the orchestrator and the registry hold references to the current jobs. I feel like the orchestrator should delegate everything to the registry, and not hold any reference locally.

Clearing up on shutdown could easily be done by calling registry methods as well.

Environment


Nest version: 0.4.0

 
For Tooling issues:
- Node version: 14.8  
- Platform: Windows 

Others:

Second intervals not divisible by 60 run irregularly

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Scheduling a Cron job that should run every X seconds where X is not divisible by 60 (ie 45) causes a another task to quickly run to fill the remaining time to 60. ie. If I run a Cron with CronExpression.EVERY_45_SECONDS I will see my function run first at 45 seconds, then 15 seconds later, then 45 seconds later, 15... etc.

Expected behavior

The function should only run every 45 seconds and should never run at 15 second intervals

Minimal reproduction of the problem with instructions

const lastRun: Moment;
@Cron(CronExpression.EVERY_45_SECONDS)
run() {
  if (!!lastRun) console.log(moment.diff(lastRun, 'seconds));
  lastRun = moment();
}

Environment


Nest version: 7.0.9
Nest Schedule version: 0.3.1

 
For Tooling issues:
- Node version: v12.16.1
- Platform:  Windows

Nest can't resolve dependencies of the SchedulerMetadataAccessor

Did you read the migration guide?

  • I have read the whole migration guide

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Potential Commit/PR that introduced the regression

N/A

Versions

1.0.2 -> 2.1.0

Describe the regression

@nestjs/schedule module is no longer working after upgrading all nestjs packages to the latest versions and node v18.7.0:

Nest can't resolve dependencies of the SchedulerMetadataAccessor (?). Please make sure that the argument Reflector at index [0] is available in the ScheduleModule context.

Minimum reproduction code

  1. package.json
    ...
    "@nestjs/apollo": "^10.0.22",
    "@nestjs/common": "^9.0.11",
    "@nestjs/config": "^2.2.0",
    "@nestjs/core": "^9.0.11",
    "@nestjs/graphql": "^10.0.22",
    "@nestjs/jwt": "^9.0.0",
    "@nestjs/platform-express": "^9.0.11",
    "@nestjs/schedule": "^2.1.0",
    "@nestjs/typeorm": "^9.0.1",
    "@types/cron": "^2.0.0",
    "apollo-server-core": "^3.10.1",
    "apollo-server-express": "^3.10.1",
    ...

  2. app.module.ts
    @module({
    imports: [ScheduleModule.forRoot(), ...],
    })

Expected behavior

Expected Nest to build when using @nestjs/schedule .

Other

No response

Uncaught exception inside cron crashes app

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Uncaught exception inside cron crashes app
https://github.com/Boshen/nestjs-playground/blob/master/src/app.service.ts#L12-L15

  @Cron(CronExpression.EVERY_SECOND)
  handleCron() {
    console.log('triggerd cron')
    throw new Error('Error')
  }
triggerd cron
/Users/boshen/github/nestjs-playground/dist/main.js:1117
        throw new Error('Error');
        ^

Error: Error
    at AppService.handleCron (/Users/boshen/github/nestjs-playground/dist/main.js:1117:15)
    at CronJob.fireOnTick (/Users/boshen/github/nestjs-playground/node_modules/cron/lib/cron.js:562:23)
    at Timeout.callbackWrapper [as _onTimeout] (/Users/boshen/github/nestjs-playground/node_modules/cron/lib/cron.js:629:10)
    at listOnTimeout (node:internal/timers:556:17)
    at processTimers (node:internal/timers:499:7)

Expected behavior

Any of these:

  • Documentation hint - user should catch the error
  • nestjs wraps it and catch the error

I've dug through node-cron and it seems they don't have a global catcher also. But as a framework we should mitigate this somehow. My production app crashed a few times ;-)

Feature request: Add a schedule task annotation that can throw errors

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

SetTimeout() is used at the bottom of the current scheduled task. If an error occurs in the scheduled task, it will not be thrown out of the method.

Expected behavior

Add a schedule annotation, try-catch by default, throw exceptions to the Nest framework.

What is the motivation / use case for changing the behavior?

We have implemented global handling of exceptions on Nest, but we found that exceptions in schedule will not be thrown. At present, we have to wrap all schedule codes with try-catch and do some things in catch. This Not the way we want.

Month index (0-11) in cron expressions: Deliberated or Mistake

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

The problem is related with the month index in cron expressions, in linux cron jobs the the month has a range between 1-12, being January the 1 and December the 12. But the @nestjs/schedule library seem like uses another format in which January is 0 and December is 11.

Is this deliberate or is it a mistake?

Current behavior

@Cron('0 12 11 1 *')

Configure a job that will be executed "At 12:00 on day-of-month 11 in February." instead january.

Expected behavior

The job will be executed in january.

Minimal reproduction of the problem with instructions

Configure a service that use the next cron:

@Cron('0 12 11 1 *', {
        name: 'test',
})
async testCron(){
        console.log('hi', new Date())
}

What is the motivation / use case for changing the behavior?

I was trying to make a job that would run every 3 months (before quarter ends), and I couldn't get it to work because in january, for example, I was using the index 1 instead 0.

Environment

# Dockerfile
ARG NODE_VERSION=14.15.1

FROM node:${NODE_VERSION}

ARG NESTJS_VERSION=7.5

WORKDIR /usr/src/project

# Install the required tools
RUN apt update;

RUN apt-get install nano;

RUN npm install -g nodemon

RUN npm install -g @nestjs/cli@${NESTJS_VERSION};

The objective of the issue is to check if this is the correct functioning, and if so, to document it.

Distributed job support

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Currently the module has very nice support for recurrent jobs on a single machine. However in an production environment it's common to have jobs that should only be done by one server every x hours, with no a priori designation for which machine this is. It would be nice if this module can support this feature.

An implementation immediately off my head would be to connect to a Redis client during initial setup. Then, whenever a server is trying to start a distributed job it would first try to acquire a Redlock corresponding to the Redis client, with the job descriptor as the key. In this way all servers will be fighting for the job, and only one will acquire the lock and actually perform it, while others just give up and do their own stuff.

Using strict mode gives an error because @types/cron are missing

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When enabling strict mode in tsconfig, it gives me the error that @types/cron are missing.

node_modules/cron/lib/cron.js' implicitly has an 'any' type.
  Try `npm install @types/cron` if it exists or add a new declaration (.d.ts) file containing `declare module 'cron';

Expected behavior

Schedule should handle it's own dependancies.

Minimal reproduction of the problem with instructions

  • Start a project
  • Install @nestjs/schedule
  • Register ScheduleModule in app module
  • Enable strict mode in tsconfig
  • npm run start:dev

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

[discussion]: Provide common cron patterns

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

import { Injectable, Logger } from '@nestjs/common';
import { Cron } 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');
  }
}

Expected behavior

Create string enums that provide a common cron syntax. For example,

export enum TaskSchedule {
  EVERY_SECOND = '* * * * * *',
  EVERY_10_SECONDS = '*/10 * * * * *',
  EVERY_30_SECONDS = '*/30 * * * * *',
  EVERY_MINUTE = '* * * * *',
  EVERY_5_MINUTES = '0 */5 * * * *',
  EVERY_10_MINUTES = '0 */10 * * * *',
  EVERY_30_MINUTES_FROM_9AM_TO_6PM = '0 */30 9-18 * * *',
  EVERY_HOUR = '0 * * * *',
  EVERY_2_HOURS = '0 */2 * * *',
  EVERY_DAY_AT_3_PM = '0 15 * * *',
  EVERY_DAY_AT_6_PM = '0 18 * * *',
  EVERY_DAY_MIDNIGHT = '0 0 0 * * *',

  ...
}

Would it be nice to define a set of widely used cron patterns?

import { Injectable, Logger } from '@nestjs/common';
import { Cron, TaskSchedule } from '@nestjs/schedule';

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

  @Cron(TaskSchedule.EVERY_30_SECONDS)
  handleCron() {
    this.logger.debug('Call every 30 seconds');
  }
}

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

I believe whenever most people, including me, when constructing cronjobs, searching for a simple pattern on https://crontab.guru/, that sometimes hard to remember is very cumbersome.

No overload matches this call error

Hello,

I'm getting the following error after installing this package.

node_modules/@types/socket.io-redis/index.d.ts:77:45 - error TS2694: Namespace '"/Users/server/node_modules/@types/socket.io-redis/node_modules/socket.io/dist/index"' has no exported member 'Adapter'.

77     interface RedisAdapter extends SocketIO.Adapter {
                                               ~~~~~~~

src/hybrid/forms/forms.entity.ts:144:31 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(inp?: MomentInput, strict?: boolean): Moment', gave the following error.
    Argument of type 'TransformFnParams' is not assignable to parameter of type 'MomentInput'.
      Type 'TransformFnParams' has no properties in common with type 'MomentInputObject'.
  Overload 2 of 3, '(inp?: MomentInput, format?: MomentFormatSpecification, strict?: boolean): Moment', gave the following error.
    Argument of type 'TransformFnParams' is not assignable to parameter of type 'MomentInput'.
  Overload 3 of 3, '(inp?: MomentInput, format?: MomentFormatSpecification, language?: string, strict?: boolean): Moment', gave the following error.
    Argument of type 'TransformFnParams' is not assignable to parameter of type 'MomentInput'.

144   @Transform((date) => moment(date).format('MM/DD/YYYY'))

My package.json

  "dependencies": {
    "@nestjs-modules/mailer": "^1.5.1",
    "@nestjs/axios": "^0.0.1",
    "@nestjs/common": "^7.5.1",
    "@nestjs/config": "0.5.0",
    "@nestjs/core": "^7.5.1",
    "@nestjs/jwt": "^7.0.0",
    "@nestjs/mongoose": "^7.1.1",
    "@nestjs/passport": "^7.1.5",
    "@nestjs/platform-express": "^7.5.1",
    "@nestjs/platform-socket.io": "7.6.13",
    "@nestjs/platform-ws": "^7.6.13",
    "@nestjs/schedule": "^1.0.1",
    "@nestjs/serve-static": "^2.1.3",
    "@nestjs/swagger": "^4.7.0",
    "@nestjs/typeorm": "^7.1.5",
    "@nestjs/websockets": "^7.6.11",
    "@types/crypto-js": "^4.0.1",
    "bcrypt": "^5.0.0",
    "cache-manager": "^3.4.0",
    "cache-manager-redis-store": "^2.0.0",
    "class-transformer": "^0.3.1",
    "class-validator": "^0.12.2",
    "crypto-js": "^4.0.0",
    "dotenv": "^8.2.0",
    "glob-parent": "^5.1.2",
    "handlebars": "^4.7.7",
    "jwk-to-pem": "^2.0.3",
    "moment": "^2.29.1",
    "mongoose": "^5.10.13",
    "mysql": "^2.18.1",
    "nanoid": "^3.1.9",
    "nest-winston": "^1.4.0",
    "nestjs-rate-limiter": "^2.7.0",
    "nestjs-stripe": "^0.4.0",
    "nestjs-twilio": "^1.0.2",
    "nodemailer": "^6.4.17",
    "passport": "^0.4.1",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "pg": "^8.5.1",
    "ramda": "^0.27.1",
    "redis": "^3.0.2",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.3.0",
    "socket.io-redis": "5.4.0",
    "stripe": "^8.132.0",
    "swagger-ui-express": "^4.1.4",
    "twilio": "^3.54.0",
    "typeorm": "^0.2.30",
    "typeorm-transactional-cls-hooked": "^0.1.20",
    "winston": "^3.3.3",
    "winston-daily-rotate-file": "^4.5.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.5.1",
    "@nestjs/schematics": "^7.1.3",
    "@nestjs/testing": "^7.5.1",
    "@types/cache-manager": "^3.4.0",
    "@types/cron": "^1.7.3",
    "@types/dotenv": "^8.2.0",
    "@types/express": "^4.17.8",
    "@types/jest": "^26.0.15",
    "@types/jwk-to-pem": "^2.0.0",
    "@types/node": "^14.14.6",
    "@types/passport-local": "^1.0.33",
    "@types/socket.io": "2.1.13",
    "@types/socket.io-redis": "1.0.27",
    "@types/supertest": "^2.0.10",
    "@types/twilio": "^2.11.0",
    "@types/ws": "^7.4.6",
    "@typescript-eslint/eslint-plugin": "^4.6.1",
    "@typescript-eslint/parser": "^4.6.1",
    "aws-sdk": "^2.695.0",
    "eslint": "^7.12.1",
    "eslint-config-prettier": "^6.15.0",
    "eslint-plugin-prettier": "^3.1.4",
    "jest": "^26.6.3",
    "prettier": "^2.1.2",
    "supertest": "^6.0.0",
    "ts-jest": "^26.4.3",
    "ts-loader": "^8.0.8",
    "ts-node": "^9.0.0",
    "tsconfig-paths": "^3.9.0",
    "tslint": "^5.20.0",
    "typescript": "^4.0.5"
  },

Exceptions not handled in cronjob functions added via SchedulerRegistry

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

When adding a cronjob by using the SchedulerRegistry, exceptions occuring inside the cron-function are not handled and cause the app to exit.
In a previous commit this behavior was fixed when using the @Cron annotation (0cdfe8f)

Minimum reproduction code

https://github.com/simon1389/nestjs-schedule-bug

Steps to reproduce

  1. npm start
  2. See the error on console and the application shutdown

Expected behavior

I expect the same behavior as when using the @Cron syntax.
So the error should be catched.

Package version

2.1.0

NestJS version

9.0.0

Node.js version

16.17.1

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Reflector can't be resolved in SchedulerMetadataAccessor

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When i'm importing the ScheduleModule in my AppModule i get the following error:

Error: Nest can't resolve dependencies of the SchedulerMetadataAccessor (?). Please make sure that the argument Reflector at index [0] is available in the ScheduleModule context.

Expected behavior

The module should work in such a simple case.

Minimal reproduction of the problem with instructions

I just installed and imported the package. Also updated every package in my project. The current environment is:
"@nestjs/bull": "^0.4.1",
"@nestjs/common": "^8.0.9",
"@nestjs/core": "^8.0.9",
"@nestjs/jwt": "^8.0.0",
"@nestjs/passport": "^8.0.1",
"@nestjs/platform-express": "^8.0.9",
"@nestjs/schedule": "^1.0.1",
"@nestjs/swagger": "^5.1.0",
"@nestjs/typeorm": "^8.0.2",

What is the motivation / use case for changing the behavior?

Environment


Nest version: 8.0.9

 
For Tooling issues:
- Node version: XX  15.8.0
- Platform:  Mac

Others:

Scheduled jobs execute multiple times

I'm submitting

[ ] Bug report

Current behavior

Every scheduled job runs multiple times.

Expected behavior

It should be triggered only once for the given cron expression

Minimal reproduction of the problem with instructions


@Cron('* * * * *')
async helloWorld() {
    console.log(new Date());
    console.log('coming');
    console.log(new Date());
}

This simple hello world scheduled job triggers multiple times every minute.

Environment


Nest version: 14.10.1

Add a CronExpression.NEVER expression

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

I want to programmatically choose the expression that I'll put in a @Cron() and sometimes (in some environments) I don't want the Cron job to execute.

Describe the solution you'd like

I'd like to have a new enum, name CronExpression.NEVER, that I can put into the @Cron

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

The motivation is that it is a clean solution. An alernative would be to use the scheduler registry in main.ts to stop the cron job, but it is less flexible.

Add nestjs/core to peer dependencies

I'm submitting a...


[ ] Regression 
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

@nestjs/core can't be resolved in my monorepo.
I get this error Cannot find module '@nestjs/core' .
I'm using lerna and yarn workspace to share modules across my packages.

@nestjs/schedule is installed in the project’s root node_modules.
@nestjs/core is installed in the node_modules of packages.
Folder architecture:
image

Expected behavior

Install @nestjs/schedule in the same folder as @nestjs/core

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Add @nestjs/core in the peer dependencies of @nestjs/schedule will fix this issue.

"peerDependencies": {
    "@nestjs/common": "^6.10.11 || ^7.0.0 || ^8.0.0",
    "reflect-metadata": "^0.1.12",
    "@nestjs/core": "^7.0.0 || ^8.0.0"
  },

Environment


Nest version: 8.Y.Z

 
For Tooling issues:
Nest version: 7.6.15

    "@nestjs/common": "^8.0.3",
    "@nestjs/config": "^1.0.1",
    "@nestjs/core": "^8.0.3",
    "@nestjs/event-emitter": "^1.0.0",
    "@nestjs/jwt": "^8.0.0",
    "@nestjs/passport": "^8.0.0",
    "@nestjs/platform-express": "^8.0.3",
    "@nestjs/schedule": "^1.0.0",
    "@nestjs/swagger": "^5.0.8",
 
For Tooling issues:
- Node version: v14.17.0
- Platform:  Mac

Others:
Using Yarn and Lerna

Replace node-cron for bree

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Petition

Change this wrapper to use bree instead node-cron, has been created by one of the maintainers (@niftylettuce)

What is the motivation / use case for changing the behavior?

Node-cron have several issues and errors, don't have good test and definitively doesn't feel confident using it.

Failed build due to lack of cron types

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

After installing and using schedule module, app doesnt build due to missing cron types

Expected behavior

Module should install all dependent packages OR documentation should point what to install

Minimal reproduction of the problem with instructions

Install nest/schedule
Use import { Cron, CronExpression } from '@nestjs/schedule';

What is the motivation / use case for changing the behavior?

node_modules/@nestjs/schedule/dist/scheduler.registry.d.ts:1:25 - error TS7016: Could not find a declaration file for module 'cron'. '/Users/lukaszostrowski/projects/app/backend/node_modules/cron/lib/cron.js' implicitly has an 'any' type.
  Try `npm install @types/cron` if it exists or add a new declaration (.d.ts) file containing `declare module 'cron';`

1 import { CronJob } from 'cron';
                          ~~~~~~

Environment


Nest version: X.Y.Z


```
[System Information]
OS Version     : macOS Big Sur
NodeJS Version : v13.7.0
NPM Version    : 6.14.9

[Nest CLI]
Nest CLI Version : 7.5.3

[Nest Platform Information]
platform-socket.io version : 7.5.1
platform-express version   : 7.5.1
serve-static version       : 2.1.3
platform-ws version        : 7.5.1
websockets version         : 7.5.1
schedule version           : 0.4.1
common version             : 7.5.1
config version             : 0.6.1
core version               : 7.5.1
cqrs version               : 7.0.1
```
 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

TypeError: date.format is not a function

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

We have a NestJS application which uses @nestjs/schedule, version 2.1.0. For deployment we use Docker images. For almost all of our deployments it works just fine. One of the client reported though, that on their onprem, the app stopped with the following error:

","stream":"stdout","time":"2022-09-08T09:37:15.496090995Z"} {"log":"/root/app/node_modules/cron/lib/time.js:271
","stream":"stderr","time":"2022-09-21T20:19:45.716126382Z"} {"log":"							Time Zone: ${zone || '\"\"'} - Cron String: ${this} - UTC offset: ${date.format(
","stream":"stderr","time":"2022-09-21T20:19:45.716202505Z"} {"log":"							 ^
","stream":"stderr","time":"2022-09-21T20:19:45.71621206Z"} {"log":"
","stream":"stderr","time":"2022-09-21T20:19:45.716218529Z"} {"log":"TypeError: date.format is not a function
","stream":"stderr","time":"2022-09-21T20:19:45.716224284Z"} {"log":" at CT._getNextDateFrom (/root/app/node_modules/cron/lib/time.js:271:79)
","stream":"stderr","time":"2022-09-21T20:19:45.716230014Z"} {"log":" at CT.sendAt (/root/app/node_modules/cron/lib/time.js:185:17)
","stream":"stderr","time":"2022-09-21T20:19:45.716245614Z"} {"log":" at CT.getTimeout (/root/app/node_modules/cron/lib/time.js:202:29)
","stream":"stderr","time":"2022-09-21T20:19:45.716251935Z"} {"log":" at CJ.start (/root/app/node_modules/cron/lib/job.js:118:31)
","stream":"stderr","time":"2022-09-21T20:19:45.716257787Z"} {"log":" at Timeout.callbackWrapper [as _onTimeout] (/root/app/node_modules/cron/lib/job.js:171:11)
","stream":"stderr","time":"2022-09-21T20:19:45.716270449Z"} {"log":" at listOnTimeout (node:internal/timers:559:17)
","stream":"stderr","time":"2022-09-21T20:19:45.716276992Z"} {"log":" at processTimers (node:internal/timers:502:7)
","stream":"stderr","time":"2022-09-21T20:19:45.71628273Z"} {"log":"npm notice 
","stream":"stderr","time":"2022-09-21T20:19:45.793334096Z"} {"log":"npm notice New minor version of npm available! 8.15.0 -> 8.19.1
","stream":"stderr","time":"2022-09-21T20:19:45.79369313Z"} {"log":"npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.19.1>
","stream":"stderr","time":"2022-09-21T20:19:45.794002242Z"} {"log":"npm notice Run `npm install -g npm@8.19.1` to update!
","stream":"stderr","time":"2022-09-21T20:19:45.794012227Z"} {"log":"npm notice 
","stream":"stderr","time":"2022-09-21T20:19:45.794136382Z"}

We have multiple @Cron annotations in our codebase, but all looks the same:

@Cron(CronExpression.EVERY_5_SECONDS, { name: DEVICE_REGISTRATION_CRON_NAME })
async exampleCron(): Promise<void> {
  this.schedulerRegistry.getCronJob(DEVICE_REGISTRATION_CRON_NAME).stop();
  try {
    // ... code that may fail, and we must not run other iteration till it finishes
  } finally {
    this.schedulerRegistry.getCronJob(DEVICE_REGISTRATION_CRON_NAME).start();
  }
}

I searched for this error, and found some similar at https://github.com/kelektiv/node-cron/issues, but those are not same, but I would say, very similar, and relates to the same bug.

What can I do? What the NestJS team will do?

Minimum reproduction code

....

Steps to reproduce

No response

Expected behavior

I would expect even if the cron fails, it would not stop the whole application.

Package version

2.1.0

NestJS version

9.0.0

Node.js version

16

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Feature request: Add an option to disable all schedule job when registering module.

I'm submitting a...


[ ] Regression 
[ ] Bug report
[X] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

What is the motivation / use case for changing the behavior?

We have a lot of tasks running with nestjs schedule via @Cron(CronExpression). I hope there is an option to disabled all cronjob/interval/timeout when registering module via ScheduleModule.forRoot({ enabled: this.configService.isProd() }). it would make development and debug specific job easier.

Or is there alternative to run specific job only during development?

Also, it would be nice we can pass default time zone via ScheduleModule.forRoot(), so user can skip pass them everytime via @Cron(CronExpression,{ timeZone: ""})

[feature idea] a parameter to disable jobs under certain conditions

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Some of my @Interval jobs should not be enabled based on some conditions. Currently I see two ways to achieve this:

  • add a "wrapper decorator" [1] that checks the condition, and if it's true, executes the @Interval decorator. Big disadvantage: the condition is checked too soon (when the js module is imported?) -- in particular, before the app's bootstrap function in main.ts even starts running, so it's not possible to initialize some conditions before building the app, or before intializing test modules in tests.
  • manually disable these jobs in SchedulerRegistry in onModuleInit or somewhere. Doesn't have the above disadvantage, but needs to be done manually and separately from the interval method, which adds some bolierplate.

Idea:

Add another optional parameter to @Interval, say options?: { enabled?: () => boolean }.

The condition function would then be checked by the scheduler before enabling the job during application bootstrap. This solves both the issues I mentioned above.

// (maybe name could then also be moved to the options object?)

It would be even better if the condition function could use injection, e.g. for some "global" config service. That could overcomplicate things though, so it wouldn't be required.

Minimal reproduction of the problem with instructions

// ---- main.ts
// <imports>
// Problem: the code below works only if this assignment would be *at the top*
// of this file, if it's below imports, the condition in `@IntervalWhen` is
// evaluated before the assignment is executed.
process.env.TEST_JOB_ENABLED = 'false'
// <app bootstrap>

// ---- some.service.ts
class SomeService {
  @IntervalWhen(() => process.env.TEST_JOB_ENABLED, 'test_job', 10000)
  async testScheduledJob(): Promise<void> { ... }
}

// ---- [1] wrapper decorator
// version 1, simple:
function IntervalWhen(
  enabled: () => boolean,
  jobName: string,
  intervalMs: number,
): MethodDecorator {
  if (enabled()) return Interval(jobName, intervalMs);
  console.log(`job ${jobName} disabled`);
  return () => {};
}

// version 2 -- thought maybe this one will evaluate the condition later, but
// the message is also logged even before application bootstrap starts
function IntervalWhen(
  enabled: () => boolean,
  jobName: string,
  intervalMs: number,
): MethodDecorator {
  return (target, key, descriptor) => {
    if (enabled()) return Interval(jobName, intervalMs)(target, key, descriptor);
    console.log(`job ${jobName} disabled`);
    return descriptor;
  }
}

What is the motivation / use case for changing the behavior?

Example use cases:

  • a job that should be enabled only on certain app instances
  • disabling some jobs in unit/e2e tests
  • probably some more, these two are the ones I'm using

References

The nest-schedule package that I've used previously has a options?: { enabled?: boolean, ... }, but since it accepts a value, not a function, it shares the disadvantage of my "wrapper decorator" approach -- the condition is evaluated too soon.

Support for running cronjob on clusters without collusion

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Expected behavior

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

[feature] Support Schedule Web UI for schedules monitoring

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Hello, Recently I've used @nestjs/schedule in project.
but I realized there is no web UI for monitoring my cronjob in this library.
I used to use Ruby on Rails, and there is a similar library aka Sidekiq.
It has supported Web UI, so I can check my cronJobs and waiting Queues.
So I would like to add Web UI for @nestjs/schedule for monitoring.

Describe the solution you'd like

If I add Web UI for @nestjs/schedule, It would be pretty simple.
There are pages that I want to make,

  • page for cronJob List in my server
  • page for waiting queues list
  • page for checking executed queues

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

It was comfortable that I check my cronjob running when I use sidekiq.
so I really hope so, NestJS also can.
And I want to make it.
of course I can check that with AWS CloudWatch but It would be good if it has visibility and Intuition.

I look forward to hearing from you favorable.
Thank you :)

Cannot add two schedule decorators to one method

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

If a method has multiple schedule decorators, only the last one is used, because the decorators save & overwrite only one SCHEDULER_TYPE under the method's metadata.

Expected behavior

All schedule decorators should be active -- or at least one per type (Interval + Timeout make some sense, two Intervals not really).

I could try to prepare a PR enabling such behavior, if you think it's a good idea.

Minimal reproduction of the problem with instructions

@Injectable()
class SomeService {
  @Interval('scheduled-log-interval', 3000)
  @Timeout('scheduled-log-first-run', 1000)
  scheduledLog(): void {
    console.log('scheduled log');
  }
}

What is the motivation / use case for changing the behavior?

Example: a periodic update every 10 minutes, with an additional timeout for a first run 30 seconds after app start.

An interval/cron job that runs periodically often also needs to have an initial run sooner, but due to "various external conditions" the initial run shouldn't be done immediately on app start.

Environment


Nest version: 6.11.4
Nest schedule version: 0.2.0

 
For Tooling issues:
- Node version: 11.9.0
- Platform: Linux

Others:

Add @Interval decorator for long running functions

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

The decorator @Interval() uses setInterval under the hood.

Expected behavior

As described in this SO answer. If the scheduled function runs longer than the time given to setInterval we may end with 2 or more executions that run concurrently. This may be a problem for 2 reasons.

  1. The concurrent executions should be forbidden because of the shared resource.
  2. To save CPU/network/RAM/...

I suggest changing the behavior. I vote for changing the behavior because the current behavior can be achieved by setting @Cron("*/10 * * * * *"). But I know changing the behavior can be problematic and it would be OK to introduce some flag to @Interval decorator or to introduce a completely new one.

Minimal reproduction of the problem with instructions

@Interval(10_000)
async handleInterval() {
  await new Promise((r) => setTimeout(r, 20_000))
  this.logger.debug('Called every 10 seconds?')
}

What is the motivation / use case for changing the behavior?

I have scheduling tasks that may take a variable amount of time to process. I would like to run processing every X minutes from the last processing and prevent processing the same resources twice. Also, I believe people don't expect this to happen but they imagine the task is running with the given delay between the executions. I saw the confusion many times. But I also know this may be just in my bubble :)

Environment


Nest version: 7.6.15
 
For Tooling issues:
- Node version: v14.15.0
- Platform:  Windows

Cannot use scheduler with NestJS 9.x

Did you read the migration guide?

  • I have read the whole migration guide

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Potential Commit/PR that introduced the regression

No response

Versions

2.1.0

Describe the regression

After upgrading NesJS core and related packages to 9.x the scheduler package doesn't work anymore. On startup the following DI error is raised:

[Nest] 1852  - 07/12/2022, 9:42:10 AM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the SchedulerMetadataAccessor (?). Please make sure that the argument Reflector at index [0] is available in the ScheduleModule context.

Potential solutions:
- If Reflector is a provider, is it part of the current ScheduleModule?
- If Reflector is exported from a separate @Module, is that module imported within ScheduleModule?
  @Module({
    imports: [ /* the Module containing Reflector */ ]
  })

Error: Nest can't resolve dependencies of the SchedulerMetadataAccessor (?). Please make sure that the argument Reflector at index [0] is available in the ScheduleModule context.

Potential solutions:
- If Reflector is a provider, is it part of the current ScheduleModule?
- If Reflector is exported from a separate @Module, is that module imported within ScheduleModule?
  @Module({
    imports: [ /* the Module containing Reflector */ ]
  })

Minimum reproduction code

  • rm -rf build
  • rm -rf node_modules
  • npm ci
  • then start an application with the scheduler included
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ScheduleModule } from '@nestjs/schedule';
import { AuthGuard, ComposeGuard, ResponseValidationCheckGuard } from './guards';

@Module({
  imports: [ScheduleModule.forRoot()],
  providers: [AuthGuard, ResponseValidationCheckGuard, { provide: APP_GUARD, useClass: ComposeGuard }],
})
export class CoreModule {}

Expected behavior

This package works with the latest NestJS version.

Other

No response

Decorators do not work in controllers

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

@Cron and other decorators work only in providers (injectables defined in providers:[]).
Documentation does not mention that decorators do not work in controllers.

Expected behavior

@Cron and other decorators work in controllers. Does it require simple change in schedule.explorer.ts with discoveryService?
If it is not possible, the docs should be explicit about this.

Minimal reproduction of the problem with instructions

  1. Create method with @Cron('* * * * * *') decorator in controller.
  2. It does not work in controllers

What is the motivation / use case for changing the behavior?

I want to define CRON method in controller alongside with manually triggered endpoint.

Environment


Nest version: 7.4.4

For Tooling issues:
- Node version: v12.13.0  
- Platform: Linux  

ScheduleExplorer will throw if a provider has a null prototype

I'm submitting a...


[ ] Regression 
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

The ScheduleExplorer will throw an unhandled promise rejection upon module initialization if the discovery service returned any providers that have a null prototype.

The provider will make it past the instance check and the error will ultimately be thrown inside the getAllFilteredMethodNames method when attempting to access properties of the null prototype:

(node:81446) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.getOwnPropertyNames (<anonymous>)
    at MetadataScanner.getAllFilteredMethodNames (/source/project/node_modules/@nestjs/core/metadata-scanner.js:24:45)
    at getAllFilteredMethodNames.next (<anonymous>)
    at new Set (<anonymous>)
    at MetadataScanner.scanFromPrototype (/source/project/node_modules/@nestjs/core/metadata-scanner.js:9:29)
    at /source/project/node_modules/@nestjs/schedule/dist/schedule.explorer.js:36:34
    at Array.forEach (<anonymous>)
    at ScheduleExplorer.explore (/source/project/node_modules/@nestjs/schedule/dist/schedule.explorer.js:30:19)
    at ScheduleExplorer.onModuleInit (/source/project/node_modules/@nestjs/schedule/dist/schedule.explorer.js:26:14)
    at MapIterator.iteratee (/source/project/node_modules/@nestjs/core/hooks/on-module-init.hook.js:21:43)
    at MapIterator.next (/source/project/node_modules/iterare/src/map.ts:9:39)
    at IteratorWithOperators.next (/source/project/node_modules/iterare/src/iterate.ts:19:28)
    at Function.from (<anonymous>)
    at IteratorWithOperators.toArray (/source/project/node_modules/iterare/src/iterate.ts:227:22)
    at callOperator (/source/project/node_modules/@nestjs/core/hooks/on-module-init.hook.js:22:10)
    at Object.callModuleInitHook (/source/project/node_modules/@nestjs/core/hooks/on-module-init.hook.js:42:23)

Expected behavior

The ScheduleExplorer gracefully handles a provider with a null prototype. Could be as simple as returning early if the prototype doesn't exist:

if (!instance || !Object.getPrototypeOf(instance)) {
  return;
}

I can open a PR with the above change if it's acceptable.

Minimal reproduction of the problem with instructions

This is reproducible using any provider created with Object.create(null). In my case, it's a custom provider that consists of a proxy where the target is an object created with Object.create(null).

What is the motivation / use case for changing the behavior?

Environment


Nest version:
@nestjs/common: 7.0.2
@nestjs/core: 7.0.2
@nestjs/schedule: 0.3.0
 
For Tooling issues:
- Node version: v12.16.1
- Platform: Mac

Others:

Circular Dependency

I'm submitting a...


[ ] Regression 
[x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Hi. I have this issue
When I added ScheduleModule.forRoot() in my AppModule, i had an error whit circular dependency. I also tried run the example https://github.com/nestjs/nest/tree/master/sample/27-scheduling, and i had the same error.
image

Environment


Nest version: 6.7.2

 
For Tooling issues:
- Node version: 12.3.1  
- Platform: Linux,

node-cron version 1.8.2 has scheduling bug

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

@nestjs/schedule is using [email protected] however issues are present with the library and current fallback is to revert to 1.7.2. See kelektiv/node-cron#478

Expected behavior

Not sure here. Maybe you could pin the 1.7.2 for now while the bug is still being investigated or a solution is provided.

Minimal reproduction of the problem with instructions

Running node-cron for enough time may crash the application. See ticket at kelektiv/node-cron#478 for more detailed information

What is the motivation / use case for changing the behavior?

Ensure stability of @nestjs/schedule

Environment


- Nest version: 7.x
- Node version: 10.x, 12.x
- Platform:  Mac, Linux

Others:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.