Run Cron Job every 45 minutes with Node-Cron

前端 未结 8 759
别那么骄傲
别那么骄傲 2020-12-25 13:58

I\'m using node-cron to run scheduled jobs. I want the jobs to run every 45 minutes, but its acting strangely

Here\'s the pattern I\'m using

\'00 */45

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 14:23

    I'm more familiar with cron than with node-cron, but I've taken a quick look at the documentation.

    If I understand it correctly, node-cron uses a syntax similar to that used by cron, but with an additional "seconds" field. So where a cron job might have:

    # min hour mday month wday command
    */15  *    *    *     *    some-command
    

    to schedule some-command to run every 15 minutes, node-cron would use a similar syntax to specify the time to run:

    '0 */15 * * * *'
    

    (with an additional field to specify seconds), but it executes a specified JavaScript function, not an external command.

    In standard cron, there is no syntax to specify running a job every 45 minutes. A specification of 0/45 * * * * would run a job twice each hour, at 0 and 45 minutes after the hour. To run a job every 45 minutes (at 00:00, 00:45, 01:30, 02:15, ..., i.e., 32 times per day) you'd have to schedule it to run every 15 minutes, and then invoke a script that checks the current time to decide whether to do anything.

    Or you can write an exhaustive list of all the times you want the job to run:

     0  0 * * * some-command
    45  0 * * * some_command
    30  1 * * * some_command
    15  2 * * * some_command
    # 28 lines omitted
    

    I'd definitely want to write a script to generate this list.

    (This is workable because 24 hours happens to be a multiple of 45 minutes. You couldn't run something every 35 minutes this way.)

    A similar approach should work for node-cron. Schedule the function to run every 15 minutes, and invoke a function that checks the current time to decide whether to run. For example, you can check whether the number of minutes since midnight modulo 45 is zero. (You might want to allow for a small variance in case the scheduling is not exact.)

    I don't know JavaScript well enough to suggest the best way to write this function, but it should be reasonably straightforward.

    Or write 32 lines to specify all the times you want it to run.

提交回复
热议问题