Vanilla NodeJS Cron Job?

Vanilla NodeJS Cron Job?

Problem Description:

I want to do something in node at, say, midnight each day.

I see a lot of stuff pointing me to node-cron, and I see this article configuring a docker container to execute a script per a crontab

I want to 1. not use any external packages and 2. keep the script being executed inside the server code itself (i.e. I couldn’t have the docker container execute some other file on a schedule)

The use case is I want to update a cache on the server every day around midnight, and then, at more frequent intervals, use that cache for various things.

Solution – 1

You can use setInterval to run the code every hour and check if it’s around midnight

setInterval(() => {
  if (new Date().getHours() === 0) {
    // do stuff
  }
}, 1000 * 60 * 60 * 60)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject