Cron jobs
Scheduling tasks for certain periods or intervals.
We could regularly check for user accounts that have been soft-deleted more than a month ago. And then, actually delete them. This may be achieved through the usage of a Cron job. Its name is inspired by the greek word for time Chronos, and allows for performing operations in a certain interval or at a specified time. Let's then get to work.
First, install the required dependency.
To maintain encapsulation, let's create a module and service for cron. In the module, import ScheduleModule.forRoot()
, and also the TypeOrmModule
to allow a repository for User
.
Now, in the CronService
, we'll create a method for removing users that have been soft-deleted more than a month ago. It may be called removeOldSoftDeletedUsers()
.
Well, to easily obtain the date for a month ago, we may use the date-fns library.
Then, use the sub()
function to subtract one month from the current date.
Finally, obtain users that are soft-deleted for more than a month, and hard-delete them.
Here, LessThan()
is used instead of MoreThan()
because we should check for dates older (lesser) than a month ago.
And now, the most important part, which is to schedule this function using a cron job. To achieve this, use the @Cron()
decorator over the method. And to execute it once a day, we can, for instance, use a CronExpression
with the value EVERY_DAY_AT_MIDNIGHT
.
For finer control, we may use cron patterns that are better described in this doc.
Commit - Using cron job to remove old soft-deleted users
Last updated