In my NestJS project, I've created a POST API to add a Date object representing the date and time for sending notifications to a mobile app.
Currently, I am working on checking which reminders have been reached for all users in order to trigger reminders to the mobile app. Below is the function implemented 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()
// Setting up an interval to continuously check reminders
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 a sleep reminder.`
)
}
}
}
}, 1000)
setTimeout(() => {
clearInterval(interval)
}, 59 * 60 * 1000)
}
}
Instead of querying the database every minute, I decided to utilize setInterval and setTimeout to check the reminders continuously. Does anyone have any recommended approaches for handling similar scenarios in other projects?