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?

