Creating a script in JavaScript to execute a command or query after midnight

I have a query regarding MongoDB and JavaScript (Express.js).

Here is the scenario:

I am working on developing a backend service for movies and TV series. I have already set up basic routes and functions. One of my requirements is to select a movie from the database and display it as "Movie Of The Day".

One of my functions is:

function filterFilmsForImdb(films, imdb){
    let filmChances = [];
    films.filter(film => {
        if(film.imdbScore >= imdb){
            filmChances.push(film);
        };
    });
    return filmChances;
};

// Movie Of The Day
function movieOfTheDay(films) {
    const date = new Date();
    if (date.getHours() >= 0) {
        let arr = filterFilmsForImdb(films, 7);
        let numberOfFilmChances = arr.length;
        let randomFilmPicker = Math.floor(Math.random() * numberOfFilmChances);
        return arr[randomFilmPicker]; // returns object (film object)
    };
};

// Recommended Films
function recommendedMovies(films){
   return  filterFilmsForImdb(films, 5);
};

I have written a function that runs after midnight (00:00), but when I refresh the page, it continues to display random data.

Is there a way to modify this function so that it only selects a movie randomly once per day?

Should I provide more details about my routes to clarify my question? Please let me know.

Answer №1

One great option for scheduling tasks in nodejs is the node-cron package.

If you want to run a function after midnight, you can use the following code snippet:

import cron from 'node-cron';
 
cron.schedule('0 0 0 * *', () => {
  console.log('executing a task at midnight');
});

Answer №2

To execute code at regular intervals, you can utilize the setInterval method.

setInterval(movieOfTheDay, 86400000);

The function movieOfTheDay will be triggered after 86400000 milliseconds (equivalent to a day in milliseconds).

It's important to note that there is no need for an if condition within the movieOfTheDay function, as date.getHours() always returns a positive value.

For more information on the setInterval method, refer to this link: reference

Answer №3

If you want to run a piece of code at midnight, one approach is to use the setInterval method to check the time every minute. Here's an example:

setInterval(function () {
    var currentDateTime = new Date();
    if(currentDateTime.getMinutes() === 0 && currentDateTime.getHours() === 0) {
        // Your code to execute at midnight goes here
    }
}, 1000);

This technique ensures that your code runs at midnight regardless of page reloads.

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

What is the best method for sending a user to a different page when a webhook is triggered by an external API in

In my project using NextJS and the pages router, I encounter a scenario where a user initiates a process through a form that takes approximately 30 seconds to complete. This process is carried out by an external API over which I have no control. Once the p ...

How can you match something once in NodeJS?

I am experiencing an issue with my HTTP NodeJS server - every time I visit the URL, it outputs the result twice. const https = require('http'); const fs = require('fs'); const url = require('url'); https.createServer((req, r ...

The Object filter is experiencing a delay with processing 10,000 items

When an API returns over 10,000 objects in the format of {firstName:'john',lastName:'Cena'}, I am faced with a performance issue. In my parent React component, I make the API call in componentDidMount and pass this object to child compo ...

Troubleshooting a JavaScript Error in AngularJS Module

I created a Module called "app" with some helper functions in the file "scripts/apps.js": angular.module('app', ['ngResource']).run(function($scope){ $scope.UTIL = { setup_pod_variables: function (pods){...} ... }); Now, I want to ...

Tips for incorporating pagination into the code sample with the query

Can someone help me with implementing items per page functionality, current and next page navigation, and fetching data in chunks from the backend using Sequelize? // controller const getdailyExpense = async (req, res) => { try { const response = ...

Leveraging typegoose in a multitenant environment within the nestjs framework

I am looking to implement multitenancy functionality where each tenant will have its own database. Can Typegoose dynamically create connections for this purpose? ...

Once the if condition is implemented, the functionality of the toggle button ceases to operate

Take a look at this demo link: http://jsbin.com/labuxuziraya/1/edit I encountered an issue where the button stops working after adding an if condition. I suspect there are some minor bugs in the code, but my level of experience is not enough to pinpoint t ...

What is the equivalent of defining conditional string types in Typescript similar to flow?

type UpsertMode = | 'add' | 'update' | 'delete'; interface IUpsertMembers { mode: UpsertMode; } const MagicButton = ({ mode: UpsertMode }) => { return ( <button>{UpsertMode}</button> ); } const Upse ...

What is the best way to dynamically adjust the height of an iframe based on its changing content

My webpage contains an iframe that loads content dynamically, and I want to center it on the page based on its height. The issue I'm facing is that while my code works well for increasing content heights, it fails to recognize when the content size de ...

Guide to changing the background colors of multiple elements when hovered over by the mouse?

I want to customize my website's search bar by changing the background color when it is hovered over. Currently, the search bar has two main elements: the text box and the submit button. I have successfully programmed the text box element to change to ...

What is the method for programmatically exporting specific tables from a MySQL database using node.js?

I need to transfer select tables from one database to another using node.js programmatically. Are there any packages or suggestions you could recommend? ...

Use regular expressions and JavaScript to enclose a series of English letters within a wrapper

I am looking to enclose a series or cluster of consecutive English characters within a <span> tag. In simpler terms, I aim to alter the appearance of English language in my writing. Therefore, I need to identify English characters and surround them ...

Using JSON / jQuery: How to Handle XML Data in the Success Function of an AJAX Post Request

Greetings! I am currently performing an ajax post through a JSP. The JSON data is being sent in string format (parsed using parseJSON, then converted back to a string using JSON stringify). The post operation functions correctly. However, my query lies in ...

Loop through each item in order to modify the text within the pop-up using a for loop

Goal Upon clicking a .player, a popup should display with relevant data about that player fetched from players.js Issue: When clicking on a player, the event seems to trigger multiple times instead of just once. This results in retrievi ...

When multiple scope (ACL) middlewares are attached to routes, only the first scope is being tested

Within my application, I have implemented 3 user scopes (User, Admin, Super Admin) manually without relying on any external ACL library. Below are the functions for admin and super admin scopes: const adminScope = (req, res, next) => { if (req.user ...

When working with app.all in Node.js, I noticed that req.body is not populated

I'm facing an issue while trying to post to /package. It's really frustrating me as I am fairly new to Node and can't seem to figure out what I'm doing wrong. Whenever I try to post to it, req.body() turns out to be empty. However, if ...

linking ng-style through live html

I am encountering an issue with dynamic data stored in the database. When trying to apply a style to a div element retrieved from the server response, I am facing difficulties with implementing it using ng-style. If the data is static, everything works fi ...

Having trouble implementing button functionality in a web app using JS, jQuery, HTML, and CSS along with an API integration

I am currently developing a web search engine that utilizes the Giphy API... However, I've encountered difficulties with the button function. I have created buttons to modify the page format and adjust the number of search results displayed.... The We ...

The "Read more" feature is not functional on mobile devices

I am encountering issues with my Wordpress blog on mobile screens. The "read more" button is not functioning, and the screen size does not fit properly on mobile devices. Visit abood250.com for more information. CSS Styling: /* =Global ----------------- ...

Issue with playing audio file using HowlerJS

Having trouble playing a .mp3 file in my project directory with Howler. I'm not sure if there's an error in my src. When I tried playing an online hosted audio file, it worked fine. I've placed the audio file in the same directory as Slideon ...