skip to Main Content

In nestjs i have a POST api to add a Date object which is the date and time to send a notification to mobile app.

So i need to check for all users, which all reminders are reached so that i need to trigger a reminder to my mobile app.

This is my function in nestjs

import { Injectable } from '@nestjs/common'
import { UserRepository } from '../auth/repositories/user.repository'
import { User } from '@vitabotx/common/entities/auth/user.entity'

@Injectable()
export class NotificationsCronService {
    constructor(private readonly userRepository: UserRepository) {}

    async sleepReminderCron() {
        const users: User[] =
            await this.userRepository.getAllUsersForSleepReminder()

        // Set up interval to check reminders continuously
        const interval = setInterval(async () => {
            const currentDate = new Date()

            for (const user of users) {
                for (const reminder of user.userReminder) {
                    if (currentDate >= reminder.time) {
                        console.log(
                            `User ${user.id} should receive sleep reminder.`
                        )
                    }
                }
            }
        }, 1000)

        setTimeout(
            () => {
                clearInterval(interval)
            },
            59 * 60 * 1000
        )
    }
}

So i thought of running a setInterval and settimeout to check every second when the time is reached or not instead of querying the DB every minute or so.

Is there any recommended way how everyother projects achieve this kind of scenario?

2

Answers


  1. You can think about using a library like bull to run cron jobs, when on each user’s reminder time, it will trigger a callback.

    Login or Signup to reply.
  2. The best actual way to manage dynamic crons (or intervals in this case) is using the @nestjs/schedule library because it is well integrated.
    You can see more about that here NestJS Intervals
    With this you can implement any cron logic (I recommend you the setInterval(callback, milliseconds) method for this problem).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search