This post has some notes and the code I did while studying nestjs. I started those notes in my first post about nestjs with simple use of the components, the second post about how to use the components and the third post regarding security with nestjs. Now, I am going a step forward to use scheduled tasks with nestjs. More detail about it you can see in the nestjs page. The code used in this post you can find inside the tasks project.
If you want some tips to calculate the time here is the crontab guru.
Cron Job
Task scheduling allows you to schedule arbitrary code (methods/functions) to execute at a fixed date/time, at recurring intervals, or once after a specified interval.
Packages to handle the tasks:
cron: from linux
Schedule: from Nestjs
node-cron: from Node.js
Agenda, Node-Schedule: MIT-licensed scheduler for Node
A comparing between some of them you can see here.
It's necessary to declare it inside your module and add the annotation inside your task to define when it should be executed. The annotation can be done using a value or a enum. Alternatively you can add parameters such as name and time zone. Also it's possible attribute intervals of execution or timeouts.
Dynamic cron job
It's possible handle the cron jobs dynamically using the SchedulerRegistry which will use the name define inside the annotation of the the task.
The same way, the SchedulerRegistry is used to register a new job dynamically.
The cron allow delete and list all the jobs.
Stackoverflow Scenarios
Scenario One
The first scenario is: how to execute a job only three times and finish it.
The solution used here is using the timeout. You have to take the period the job has to execute and multiply by how many rounds you want to execute. Also, the example is using the dynamic mode to have the values as parameters.
So, considering the intervals of execution is each 2 seconds and you want this job execute 3 times, the limit of time used will be 2 * 3 * 1000. The job will stop after 6 seconds after the start.