nestjs/schedule

Add @Interval decorator for long running functions

miso-belica opened this issue · 1 comments

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

@Interval() and @Timeout() decorators act as very basic wrappers for setInterval and setTimeout functions. We intentionally haven't added any extra features on top of that. If one needs more sophisticated logic, we'd recommend using a cron/custom implementation/different lib

Apologies for any inconvenience!