Home > Enterprise >  Trigger a function at particular time everyday in javascript
Trigger a function at particular time everyday in javascript

Time:10-05

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.

CodePudding user response:

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.

CodePudding user response:

You can try smth like this, after component rendered setInterval function will check if it is you birthday now or not.But you need to work with ms parameter(now it will check every 5s).And also add some trigger to invoke clearInterval.For example one more useEffect with [your flag] as parameter.

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(checkBirthday, 5000);
        return () => clearInterval(id);
    },
    []
);

return <div></div>;
};
  • Related