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.
yarn add @nestjs/scheduleTo 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.
nest g mo cron
nest g s cronNow, 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.
yarn add date-fnsThen, use the sub() function to subtract one month from the current date.
const oneMonthAgo = sub(new Date(), { months: 1 });Finally, obtain users that are soft-deleted for more than a month, and hard-delete them.
const users = await this.usersRepository.find({
where: {
registryDates: { deletedAt: LessThan(oneMonthAgo) },
},
withDeleted: true,
});
await this.usersRepository.remove(users);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 use a CronExpression with the value EVERY_DAY_AT_MIDNIGHT, for instance.
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)For finer control, we may use cron patterns that are better described in this NestJS doc.
Commit - Using cron job to remove old soft-deleted users
Last updated