Trigger a function at particular time everyday in javascript

Viewed 422

I'm creating a birthday app where I want to trigger a function at a particular time Eg. At 6 AM. But I'm not getting any idea of how to implement that. Please give a suggestion. Using react as frontend and express as backend and database I use MongoDB. Also, any code reference will help .Thank you in advance.

2 Answers

You can try smth like this, after component rendered setInterval function will check if it is your birthday now or not.Finally, in right moment will invoke some func and disable itself.

import React, { useEffect } from 'react';

const BirthDay = () => {

const date = new Date('2022-12-17T03:24:00') //your birthday here
const birthdayFunc = () => {console.log('Birthday!!!')}
const checkBirthday = () => {
    if(new Date() >= date) birthdayFunc()
    else return
}

useEffect(
    () => {
        const id = setInterval(function()
        {
           if(new Date() >= date) 
           {
              birthdayFunc()
              clearInterval(id)
           }
           else return
        }, 1000);
        return () => clearInterval(id);
    },
    []
);

return <div></div>;
};

A solution can be using a job scheduler such as crontab on Linux machine. If its Windows, cron is called scheduled tasks and It's in the Control Panel. It allows to trigger periodically perform a task.

Related