'Trigger a function on the start of a new day in javascript

Everyday I need to trigger a function on the start of a new day. How do I do that in Javascript? I have a desktop application made on electron js. I am logging necessary logs in a log file. I am creating new log file every new day. But i need to zip log file every new day. So i want to trigger a function which is used for zipping log file on the start of a new day.



Solution 1:[1]

You have the following solutions, its depend on how your applications works

  • Your app is running on servers that you control -> Use cron

  • Your app is always online -> if its nodejs search for cronjob in npm packages, if its pure js work witch setTimeout/setInterval

  • Your app is reachable from outside -> Run a cronjob on a remote server to ping your application, or simply set a daily job on zappier/powerautomate to ping your application

  • Your app is not reachable from outside, not always online, and you dont want cron -> Manage logs when starting applications + use solution 1 when its oline

Solution 2:[2]

We have two options here:

  • Server Side [server is always up and running]
  • Clinet Side [web app needs to be executed/opened by an end user]

in server side, we have a very good package called node-schedule

but on the client side, we can use setTimeout and some normal time calculations to call a function after certain amount of time like given example.

const currDate = new Date();

// this will give the current time in ms
const currTime = currDate.getTime();

// increase the date by 1
currDate.setDate(currDate.getDate() + 1);

// set hours, mins, seconds to the 0 [as setHours can accepts (hours, mins, seconds, miliseconds), we can pass all the parameters at once]
currDate.setHours(0, 0, 0, 0);

// now currDate holds the time for midnight
const midnightTime = currDate.getTime();

// create a setTimeout function for the time difference
const diff = midnightTime - currTime;
console.log(`Code will be triggered after: ${diff}ms`);
setTimeout(() => {
  // your code goes here
}, diff);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daphoque
Solution 2 geekyorion