Home > Web Front-end > JS Tutorial > How to shedule a task in Node.js using Node Cron

How to shedule a task in Node.js using Node Cron

DDD
Release: 2025-01-05 20:21:41
Original
198 people have browsed it

How to shedule a task in Node.js using Node Cron

__To handle a delayed deletion request (e.g., deleting a user profile after 5 days), you can achieve this in Node.js using a delayed task scheduling approach. Here’s a step-by-step implementation:

Approach 1: Using a Background Task Scheduler (e.g., node-cron or Agenda.js)
Example with node-cron:

  1. Install the package: npm install node-cron Code to Shedule Deletion const cron = require("node-cron"); const User = require("../models/User"); // Assume User is your Mongoose model

exports.deleteProfile = async (req, res) => {
try {
const { userId } = req.body;

// Validate input
if (!userId) {
  return res.status(400).json({ success: false, message: "User ID is required" });
}

// Find user to ensure existence
const user = await User.findById(userId);
if (!user) {
  return res.status(404).json({ success: false, message: "User not found" });
}

// Schedule deletion after 5 days
const deletionDate = new Date();
deletionDate.setDate(deletionDate.getDate() + 5);

cron.schedule(deletionDate.toISOString(), async () => {
  await User.findByIdAndDelete(userId);
  console.log(`User with ID ${userId} deleted successfully.`);
});

return res.status(200).json({
  success: true,
  message: `User deletion scheduled for ${deletionDate.toISOString()}`,
});
Copy after login

} catch (error) {
console.error("Error scheduling deletion:", error);
return res.status(500).json({ success: false, message: "Internal Server Error" });
}
};

The above is the detailed content of How to shedule a task in Node.js using Node Cron. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template