Guide to creating a reminder feature in NestJS

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?

Answer №1

Consider implementing a tool such as bull to schedule and execute periodic tasks for users, triggering specific actions at designated reminder intervals.

Answer №2

For effectively managing dynamic crons (or intervals), the recommended approach is to utilize the @nestjs/schedule library due to its seamless integration. To learn more about this, check out the documentation on NestJS Intervals This method allows you to easily implement any cron logic by utilizing the

setInterval(callback, milliseconds)
function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node app experiencing port exhaustion within Azure Function

Currently, I am in the process of developing an Azure Function that is responsible for making a high volume of outgoing HTTP requests. However, I have noticed that periodically it reaches a limit where all requests time out for a brief period of a couple m ...

Improving an unspecified JavaScript function

After taking inspiration from another website, I incorporated this code snippet into my project, only to find that it's not functioning properly. What could be the issue? var LessonsCustomControl = (function LessonsCustomControl_constructor(){ va ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Issues with AJAX function not being successfully transmitted

When the timer ends, I want to display a "Not active" message instead of "Active". The timer and code appear to be functioning properly until this point $('.clock').eq().countdown(inputDate). After this line of code, the function stops working an ...

Navigating with React-router can sometimes cause confusion when trying

I'm having trouble with my outlet not working in react-router-dom. Everything was fine with my components until I added the Outlet, and now my navigation component isn't showing even though other components are rendering. import Home from ". ...

I need guidance on how to successfully upload an image to Firebase storage with the Firebase Admin SDK

While working with Next.js, I encountered an issue when trying to upload an image to Firebase storage. Despite my efforts, I encountered just one error along the way. Initialization of Firebase Admin SDK // firebase.js import * as admin from "firebas ...

Creating interactive checkboxes dynamically using form data - a step-by-step guide

Scenario When a user fills out an order form, they have the option to choose a bike type and select from the corresponding options available for that bike type. Current Issue I am facing a situation where I need to include a checkbox with all possible op ...

Having trouble passing a token for authentication in Socket.IO v1.0.x?

I am currently following a tutorial on creating a token-based authentication system, which can be found here. I have implemented the following code: Code in app.html: var socket = io('', { query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R" }); ...

The TypeScript `unknown` type restricts the use of non-unknown types in function parameters

Why is there an error in this code? const x: unknown[] = ['x', 32, true]; // OK const y: (...args: unknown[]) => unknown = (xx: number) => {}; // ERROR // Type '(xx: number) => void' is not assignable to type '(...args: u ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

"Adding dots" in a slideshow using HTML, CSS, and JS

I'm currently working on a slideshow that includes navigation dots at the bottom. Although the slideshow is functioning properly, I am encountering an issue where only one dot appears instead of the intended three in a row. Despite my research and att ...

Double Assignment in JavaScript

Can you explain the concept of double assignment in ExpressJS and its functionality? An illustration is provided below using a code snippet from an ExpressJS instance. var server = module.exports = express() ...

Adjusting the size of a Video/Image Slider to perfectly fit the screen dimensions (both width and height

I have been using a slider code to display my images and videos. The code can be found here: Code:https://codepen.io/1wdtv/pen/jbjZeb The issue I am facing is that the slider is only responsive in terms of width. This means that when resizing the browser ...

Changing a get request to a post request: A step-by-step guide

I have been utilizing the following script: $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', start: function(){ $("#success-result").html("loading...."); }, update : function ( ...

What are the necessary headers that must accompany a post request?

While testing the server with Postman, everything seems to be working fine as I receive a response: https://i.stack.imgur.com/yMRfj.png However, when attempting to make a POST request from the browser using the same address, it results in an error and th ...

What is the best way to link to this list of options?

#episode-list { padding: 1em; margin: 1em auto; border-top: 5px solid #69c773; box-shadow: 0 2px 10px rgba(0,0,0,.8) } input { width: 100%; padding: .5em; font-size: 1.2em; border-radius: 3px; border: 1px solid #d9d9d9 } <div id="epis ...

Unable to incorporate an external JavaScript file via a static URL

I'm attempting to link an external javascript file using a static URL, like this: <script type="text/javascript" src="{{ url_for('static/js', filename='test.js') }}"></script> However, I am encountering the following ...

"Exploring the dynamic features of jQuery's mobile listview and

As I work on creating a mobile app using jQuery Mobile, I find myself facing some challenges. Despite my efforts and attempts at different methods, I have not been successful in achieving the desired functionality. Specifically, I am trying to implement a ...

Guidance that utilizes the scope of a specific instance

I have successfully created a d3.js directive, but I am facing an issue when resizing the window. The values of my first directive seem to be taking on the values of my second directive. How can I separate the two in order to resize them correctly? (both ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...