Search code examples
javascripttypescriptcronsettimeoutnestjs

what is good way to run a code after x hours after an API is called?


I am building a nest web app with typescript.

I would like to execute some function x hrs after API is called but not sure how I can achieve this.

Because I want to run a function only once, I think I can use setTimeout, but it that a good idea? I was thinking to use cron, but as far as I understand, cron is to set a schedule and it will be repeated (correct me if I am wrong)

Any advice would be appreciated!


Solution

  • You can use a Cron Job. https://docs.nestjs.com/techniques/task-scheduling#declarative-timeouts

    If you read the documentation, it says that you could create a cronJob that executes after X milisseconds.

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

    So, you have to call this function when your API is called, then it would execute after X hours.