---
description: Scheduling tasks for certain periods or intervals.
---

# Cron jobs

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.

```sh
yarn add @nestjs/schedule
```

To maintain encapsulation, let's create a module and service for **cron**. In the module, import <mark style="color:blue;">`ScheduleModule.forRoot()`</mark>, and also the <mark style="color:blue;">`TypeOrmModule`</mark> to allow a repository for <mark style="color:blue;">`User`</mark>.

```sh
nest g mo cron
nest g s cron
```

Now, in the <mark style="color:blue;">`CronService`</mark>, we'll create a method for removing users that have been soft-deleted more than a month ago. It may be called <mark style="color:blue;">`removeOldSoftDeletedUsers()`</mark>.

Well, to easily obtain the date for a month ago, we may use the **date-fns** library.

```sh
yarn add date-fns
```

Then, use the <mark style="color:blue;">`sub()`</mark> function to **subtract** one month from the current date.

```typescript
const oneMonthAgo = sub(new Date(), { months: 1 });
```

Finally, obtain users that are soft-deleted for more than a month, and hard-delete them.

```typescript
const users = await this.usersRepository.find({
  where: {
    registryDates: { deletedAt: LessThan(oneMonthAgo) },
  },
  withDeleted: true,
});

await this.usersRepository.remove(users);
```

{% hint style="info" %}
Here, <mark style="color:blue;">`LessThan()`</mark> is used instead of <mark style="color:blue;">`MoreThan()`</mark> because we should check for dates **older** (lesser) than a month ago.
{% endhint %}

And now, the most important part, which is to **schedule** this function using a **cron job**. To achieve this, use the <mark style="color:blue;">`@Cron()`</mark> decorator over the method. And to execute it once a day, we can use a <mark style="color:blue;">`CronExpression`</mark> with the value <mark style="color:blue;">`EVERY_DAY_AT_MIDNIGHT`</mark>, for instance.

```typescript
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
```

> For finer control, we may use **cron patterns** that are better described in this [NestJS doc](https://docs.nestjs.com/techniques/task-scheduling#declarative-cron-jobs).

<mark style="color:green;">**Commit**</mark> - Using cron job to remove old soft-deleted users
