skip to Main Content

Is there any way I can execute the function at the exact minute (1 and 31 minutes for example ) every hour?
For example, it should be executed at:

08:01
08:31
09:01
09:31
10:01
...

3

Answers


  1. You could have a look at something like Croner, this can evaluate and run Cron expressions.

    This package can also return a list of the next N runtimes for a cron expression.

    Crontab.guru is handy for parsing these expressions too.

    For your example, the cron expression will look like `1,31 * * * *’, meaning it will run at every minute and at thirty-one minutes past every hour.

    const pattern = '1,31 * * * *'
    
    const job = Cron(pattern, () => {
      console.log('Job is running...');
    });
    
    const nextTimes = Cron(pattern).nextRuns(10);
    console.log('Next run times:', nextTimes.map(d => d.toLocaleTimeString()));
    .as-console-wrapper { max-height: 100% !important; }
    <script src="https://cdn.jsdelivr.net/npm/croner@6/dist/croner.umd.min.js"></script>
    Login or Signup to reply.
  2. You can use a cron to do that, or do it from scratch with a setInterval to create a timer that will execute a callback every n millisecond (in your case every 60000).

    Then in the callback you will only have to check the value of new Date().getMinutes() (1 or 31) and execute the function if the condition pass

    setInterval(() => {
      const currentMinutes = new Date().getMinutes();
      if([1, 31].includes(currentSeconds) {
        // ...
      }
    }, 60000);
    

    If you want the function to be called at exactly 0 second, you can start with a setInterval executing the callback every second until the next minute, then use the above method

    For example:

    function forEveryMinutes() {
      setInterval(() => {
        const currentMinutes = new Date().getMinutes();
        if([1, 31].includes(currentSeconds) {
          // ...
        }
      });
    };
    
    const secondsInterval = setInterval(() => {
      const currentSeconds = new Date().getSeconds();
      if(!currentSeconds) {
        clearInterval(secondsInterval);
        forEveryMinutes();
      }
    }, 1000);
    
    Login or Signup to reply.
  3. Basically if you use setInterval or any other javascript package, keep it in mind that it will work only when the page is opened. Otherwise it will not work.

    So, let say in your application, you have subscription system. Now whether user has opened the application or not, you have to expired subscription after specific time period. So, for these cases, you can’t use javascript.

    Now for these cases, you need corn job. You can also use Database Triggers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search