---
# System prepended metadata

title: 'Update database, Add scheduler and scheduled job'

---

# Update database, Add scheduler and scheduled job

### Unit Test
![](https://i.imgur.com/ImcyZGn.png)

### Updated database
![](https://i.imgur.com/Rccptaj.png)

### Updated controller and routes
```typescript=
export const setExpiredDonationSql = `
UPDATE donation_items 
SET 
    status = 'Closed' 
WHERE 
    expired_date < now() AND status='Ongoing'
RETURNING id`;


createDonationItem = (donationItem: DonationItem) => {
    return new Promise((resolve, reject) => {
      // Generate Donation ID
      var donationId = "DN-" + this.nanoid();

      // Insert donation item to database
      db.oneOrNone(insertDonationItemSql, [
        donationId,
        donationItem.getUid(),
        donationItem.getTitle(),
        donationItem.getDescription(),
        donationItem.getTotalNominal(),
        donationItem.getImageUrl(),
        donationItem.getExpiredDate(),
      ])
        .then((data: any) => resolve(data))
        .catch((error: any) => reject(error));
    });
  };

  updateDonationItem = (donationItem: DonationItem) => {
    return new Promise((resolve, reject) => {
      // Update donation item in database
      db.oneOrNone(updateDonationItemSql, [
        donationItem.getTitle(),
        donationItem.getDescription(),
        donationItem.getTotalNominal(),
        donationItem.getImageUrl(),
        donationItem.getExpiredDate(),
        donationItem.getId(),
        donationItem.getUid(),
      ])
        .then((data: any) => resolve(data))
        .catch((error: any) => reject(error));
    });
  };
  
setExpiredDonation = () => {
    return new Promise((resolve, reject) => {
      db.manyOrNone(setExpiredDonationSql)
        .then((data: any) => (data.length > 0 ? resolve(true) : resolve(false)))
        .catch((error: any) => reject(error));
    });
  };
```

### Sceduler and Sceduled job
```typescript=
// Initialize cron job
// Check expired donation at 00.05 everyday
const job = new CronJob(
  "5 0 * * * *", // CRON string
  () => {
    new DonationController()
      .setExpiredDonation()
      .then((data: any) =>
        console.log(
          (data as boolean)
            ? "Success update expired data"
            : "No expired donation items"
        )
      );
  },
  () => {
    console.log("task completed" as string);
  }
);

// Start cron job
job.start();
console.log("CronJob started");
```