nestjs / schedule Goto Github PK
View Code? Open in Web Editor NEWSchedule module for Nest framework (node.js) ⏰
Home Page: https://nestjs.com
License: MIT License
Schedule module for Nest framework (node.js) ⏰
Home Page: https://nestjs.com
License: MIT License
[ ] 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.
@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:
Install @nestjs/schedule
in the same folder as @nestjs/core
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"
},
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
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
.circleci/config.yml
cimg/node 21.6
cimg/node 21.6
package.json
cron 3.1.6
uuid 9.0.1
@commitlint/cli 19.2.2
@commitlint/config-angular 19.2.2
@nestjs/common 10.3.7
@nestjs/core 10.3.7
@nestjs/platform-express 10.3.7
@nestjs/testing 10.3.7
@types/jest 29.5.12
@types/node 20.12.7
@types/sinon 17.0.3
@types/uuid 9.0.8
@typescript-eslint/eslint-plugin 7.6.0
@typescript-eslint/parser 7.6.0
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.2
release-it 17.2.0
rimraf 5.0.5
rxjs 7.8.1
sinon 17.0.1
ts-jest 29.1.2
typescript 5.4.5
@nestjs/common ^8.0.0 || ^9.0.0 || ^10.0.0
@nestjs/core ^8.0.0 || ^9.0.0 || ^10.0.0
[ ] 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.
Scheduled Tasks not running when injected or nested service has @Injectable({ scope: Scope.REQUEST })
Scheduled Tasks running normally.
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,
) {
}
}
If a service with Scope.REQUEST is not supported OK, but that should not stop Scheduled Services to work.
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.
[ ] 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.
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.
The module should work in such a simple case.
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",
Nest version: 8.0.9
For Tooling issues:
- Node version: XX 15.8.0
- Platform: Mac
Others:
[ ] 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.
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.
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.
@Injectable()
class SomeService {
@Interval('scheduled-log-interval', 3000)
@Timeout('scheduled-log-first-run', 1000)
scheduledLog(): void {
console.log('scheduled log');
}
}
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.
Nest version: 6.11.4
Nest schedule version: 0.2.0
For Tooling issues:
- Node version: 11.9.0
- Platform: Linux
Others:
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.
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"
},
[ ] 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.
@Cron
and other decorators work only in providers (injectables defined in providers:[]
).
Documentation does not mention that decorators do not work in controllers.
@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.
@Cron('* * * * * *')
decorator in controller.I want to define CRON method in controller alongside with manually triggered endpoint.
Nest version: 7.4.4
For Tooling issues:
- Node version: v12.13.0
- Platform: Linux
[ ] 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.
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 (
schedule/lib/decorators/cron.decorator.ts
Line 21 in 4164efe
Thanks,
[ ] 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.
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.
The function should only run every 45 seconds and should never run at 15 second intervals
const lastRun: Moment;
@Cron(CronExpression.EVERY_45_SECONDS)
run() {
if (!!lastRun) console.log(moment.diff(lastRun, 'seconds));
lastRun = moment();
}
Nest version: 7.0.9
Nest Schedule version: 0.3.1
For Tooling issues:
- Node version: v12.16.1
- Platform: Windows
[ ] 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.
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';
Schedule should handle it's own dependancies.
Nest version: X.Y.Z
For Tooling issues:
- Node version: XX
- Platform:
Others:
[ ] 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.
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)
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.
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)
.
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:
[ ] 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.
The decorator @Interval()
uses setInterval
under the hood.
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.
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.
@Interval(10_000)
async handleInterval() {
await new Promise((r) => setTimeout(r, 20_000))
this.logger.debug('Called every 10 seconds?')
}
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 :)
Nest version: 7.6.15
For Tooling issues:
- Node version: v14.15.0
- Platform: Windows
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?
....
No response
I would expect even if the cron fails, it would not stop the whole application.
2.1.0
9.0.0
16
No response
[ ] 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.
Nest version: X.Y.Z
For Tooling issues:
- Node version: XX
- Platform:
Others:
No response
2.1.0
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 */ ]
})
rm -rf build
rm -rf node_modules
npm ci
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 {}
This package works with the latest NestJS version.
No response
[ ] 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.
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.
Nest version: 6.7.2
For Tooling issues:
- Node version: 12.3.1
- Platform: Linux,
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.
If I add Web UI for @nestjs/schedule, It would be pretty simple.
There are pages that I want to make,
No response
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 :)
[ ] 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.
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.
Use redis, like @nestjs/websockets do, to save/create schedules
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
[ ] 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.
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...
getCroneJob should find a job for given name.
Nest version: 7.4.1
For Tooling issues:
- Node version: v12.18.3
- Platform: Mac
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.
I have two ideas:
@Cron
decorator.
Non-breaking
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.
[ ] 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.
[ ] 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.
@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
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.
Running node-cron for enough time may crash the application. See ticket at kelektiv/node-cron#478 for more detailed information
Ensure stability of @nestjs/schedule
- Nest version: 7.x
- Node version: 10.x, 12.x
- Platform: Mac, Linux
Others:
[ ] 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.
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 -> ]
Importing the ScheduleModule shouldn't produce a circular dependency problem
@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 });
}
}
}
fix a bug
Nest version: 6.10.5
For Tooling issues:
- Node version: 10.16.3
- Platform: Mac
Others:
[ ] 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.
Change this wrapper to use bree instead node-cron, has been created by one of the maintainers (@niftylettuce)
Node-cron have several issues and errors, don't have good test and definitively doesn't feel confident using it.
[ ] 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.
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.
Add a schedule annotation, try-catch by default, throw exceptions to the Nest framework.
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.
[ ] 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.
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');
}
}
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');
}
}
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.
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)
https://github.com/simon1389/nestjs-schedule-bug
I expect the same behavior as when using the @Cron
syntax.
So the error should be catched.
2.1.0
9.0.0
16.17.1
No response
N/A
1.0.2 -> 2.1.0
@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.
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",
...
app.module.ts
@module({
imports: [ScheduleModule.forRoot(), ...],
})
Expected Nest to build when using @nestjs/schedule .
No response
[ ] 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.
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: ""})
[ ] 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.
Any job created with SchedulerRegistry
is not being cleared on application shutdown.
All jobs, both those declared with decorators, and those declared with the Dynamic API, should be cleared on shutdown.
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));
}
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.
Nest version: 0.4.0
For Tooling issues:
- Node version: 14.8
- Platform: Windows
Others:
[ ] 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.
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...
...interval after last task finished. Essentially something like "run a new task 10 seconds after the previous task has finished".
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.
[ ] 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.
Some of my @Interval
jobs should not be enabled based on some conditions. Currently I see two ways to achieve this:
@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.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.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.
// ---- 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;
}
}
Example use cases:
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.
[ ] 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?
@Cron('0 12 11 1 *')
Configure a job that will be executed "At 12:00 on day-of-month 11 in February." instead january.
The job will be executed in january.
Configure a service that use the next cron:
@Cron('0 12 11 1 *', {
name: 'test',
})
async testCron(){
console.log('hi', new Date())
}
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.
# 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.
[ ] 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.
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).
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).
Just clone it and run yarn && yarn build
.
Nest version: 7.0.7
For Tooling issues:
- Node version: v12.16.1
- Platform: Mac
Others:
[ ] 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.
Cannot set runOnInit by Cron decorator
https://github.com/nestjs/schedule/blob/master/lib/decorators/cron.decorator.ts#L22
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
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.
Nest version: 7.4.2
For Tooling issues:
- Node version: 12
- Platform: Windows
Others:
[ ] 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.
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
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
"@nestjs/common": "^6.10.13",
"@nestjs/config": "0.0.7",
"@nestjs/core": "^6.10.13",
"@nestjs/schedule": "^0.1.1",
[ ] 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.
0|server | [Nest] 2026877 - 01/25/2021, 12:00:00 PM [Scheduler] Object:
0|server | {}
0|server | +10ms
the error object or error message
just throw error inside scheduled function
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:
[ ] 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.
After installing and using schedule module, app doesnt build due to missing cron types
Module should install all dependent packages OR documentation should point what to install
Install nest/schedule
Use import { Cron, CronExpression } from '@nestjs/schedule';
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';
~~~~~~
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:
[ ] 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.
Always start the cronjob on application bootstrap
https://github.com/nestjs/schedule/blob/master/lib/scheduler.orchestrator.ts#L81
There is an options to start the cronjob on application bootstrap or not
if(options.runOnApplicationBootstrap) {
cronJob.start();
}
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.
Nest version: 7.4.2
For Tooling issues:
- Node version: 12
- Platform: Windows
Others:
[ ] 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.
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)
Any of these:
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 ;-)
Improve unhandled exceptions inside cron tasks.
Use cron name if provided as context for log.error message.
Update:
schedule/lib/schedule.explorer.ts
Line 125 in 73f46ad
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
Not sure about add any tip about this in doc.
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.
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.
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.
I'd like to have a new enum, name CronExpression.NEVER
, that I can put into the @Cron
No response
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.
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.
[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
https://github.com/nestjs/schedule.git
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
RUN npm install @nestjs/cli -g
RUN npm install
RUN npm run build
COPY . .
CMD ["node", "dist/main"]
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');
}
}
8.1.3
No response
No response
No response
[ ] Bug report
Every scheduled job runs multiple times.
It should be triggered only once for the given cron expression
@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.
Nest version: 14.10.1
[ ] 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.
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.
The cronjobs should always only run only once.
@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);
// });
}
The current implementation for me results in sending multiple events to webengage which in turn sends multiple notifications to the users.
Nest version: 7.5.4
For Tooling issues:
- Node version: 12.18.2 -->
- Platform: Mac
Others:
Using npm version 6.14.5
[ ] 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 depends on cron
remove cron, use node-cron instead.
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.
Nest version: X.Y.Z
For Tooling issues:
- Node version: XX
- Platform:
Others:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.