Home > other >  How to schedule a function to run at a certain date?
How to schedule a function to run at a certain date?

Time:11-01

I have a website that allows users to send themselves a message at a date they choose, but I have no idea how to send it at that specific time. I know there exist CronJobs, but here, I'm not doing anything recurring. It's a one-time event trigger that I need.

I first tried using the native setTimeout like this:

const dueTimestamp = ...; 
const timeLeft = dueTimestamp - Date().now(); 
const timeoutId = setTimeout(() => sendMessage(message), timeLeft);

It works perfectly for short periods, however, I'm not sure if it is reliable for long periods such as years or even decades. Moreover, it doesn't offer much control because if I'd like to modify the dueDate or the message's content, I'd have to stop the Timeout and start a new one.

Is there any package, a library, or a service that allows you to run a NodeJS function at a scheduled time? or do you have any solutions? I've heard of Google Cloud Schedule or Cronhooks, but I'm not sure.

CodePudding user response:

You can use node-schedule library. for example : you want to run a funcation at 5:30am on December 21, 2022.

const schedule = require('node-schedule');
const date = new Date(2022, 11, 21, 5, 30, 0);

const job = schedule.scheduleJob(date, function(){
  console.log('The world is going to end today.');
});

CodePudding user response:

As recommended by user3425506, I simply used a Cron job to fetch the messages from a database and to send the message of those whose timestamps have passed.

Dummy representation:

import { CronJob } from "cron";
import { fakeDB } from "./fakeDB";

const messages = fakeDB.messages;

const job = new CronJob("* * * * * *", () => {
  const currentTimestamp = new Date().getTime();

  messages.forEach((message, index) => {
    if (message.timestamp > currentTimestamp) return;

    console.log(message.message);

    messages.splice(index, 1);
  });
});

job.start();
  • Related