I am developing a Node.js application that includes a scheduled task intended to trigger a webhook only when specific tasks are due. The scheduling is set to check for due tasks every minute, which is functioning correctly. However, the webhook is being triggered at every scheduled interval, even when there are no due tasks, and often it sends requests without any data. This behavior occurs despite the expectation that the webhook should only activate when a task's due conditions are met.
Here's a simplified version of the relevant part of my code, with sensitive data removed:
// Express app setup, body parsing, cors, logging
// MongoDB connection setup
// Schema and model definition
const schedule = require("node-schedule");
const axios = require("axios");
// Utility function to check if a task is due
const isTaskDue = (taskDate, taskTime) => {
// Implementation...
};
// Function to check the database for due tasks and trigger webhook
const checkForScheduledTasks = async () => {
const tasks = await FormData.find({});
tasks.forEach(async (task) => {
if (isTaskDue(task.date, task.time)) {
await axios.post("WEBHOOK_URL", task); // Triggering the webhook
await FormData.deleteOne({ _id: task._id }); // Delete the task from the database
}
});
};
// Schedule the task checking to run every minute
schedule.scheduleJob("* * * * *", checkForScheduledTasks);
I expected the checkForScheduledTasks function to only trigger the webhook when it finds a task that is due based on the isTaskDue function's evaluation. However, the webhook is being triggered every minute by the scheduler, regardless of whether tasks are due or not, resulting in unnecessary requests, some of which contain no data.
I've reviewed the scheduling logic and the task due check implementation but haven't identified why the webhook is triggered even when there should be no due tasks. I was considering whether the issue might be related to how the scheduled tasks are fetched and evaluated, or possibly something related to the asynchronous handling of tasks within the scheduled job.