how can i stop node-cron job after some time have passed automaticaly

42 Views Asked by At

it enters the else statment but it doesn't stop and it keep printing end

var job= cron.schedule('* * * * * *', () => {
    let currentDate = new Date()
    let stopDate = new Date("2024-01-19T14:56:00.000Z")
    if (currentDate < stopDate) {
        console.log("hi")
    }
    else {
        console.log("end")
        job.stop();
    }
});
1

There are 1 best solutions below

0
faghihy On

The issue with your code is that you are comparing the current date (currentDate) to the stop date (stopDate) within the callback function of the cron job. However, since the cron job runs every second ('* * * * * *'), the comparison will always be true, and the else block will never be executed. You are not using the cron jobs in the right way. Bring your if statement outside the cron job.