Search code examples
javascriptnode.jsreactjscron

Cron-parser settings for every second(n) week node js


I'm using the cron-parser library in Node.js to handle cron scheduling in my application. I have a requirement where I need to set up a cron job that runs every two weeks, specifically on Mondays and Sundays.

I've looked into the documentation for cron-parser, but I couldn't find any direct support for this type of schedule. The library seems to follow the standard cron syntax. Is there a way to configure cron-parser to achieve this every two weeks pattern while targeting specific weekdays?

For context, my current approach involves parsing a custom schedule format like (7,1)/2, where 7 represents Sunday and 1 represents Monday. This approach works, but I'm wondering if there's a cleaner or more standard way to achieve this using cron-parser.

Here's the relevant part of my code:

const parser = require('cron-parser');

// Custom schedule format: (7,1)/2 (for Sundays and Mondays every two weeks)
const scheduleData = '(7,1)/2';
const interval = parser.parseExpression(scheduleData, {
  // ...
});

Any insights, suggestions, or alternative approaches to achieve this type of schedule would be greatly appreciated!


Solution

  • Since i needed on node js and i was using cron-parser what i did is create a custom cron 1 10 * * [1,7] 2(this is n week)

    then i splitted on " " took index 5 of element to take the n week

    i was using also dayjs so i used weekOfYear plugin(https://day.js.org/docs/en/plugin/week-of-year) to take what week im currently in and checked if number of week % n is 0 then we should format the cron to 1 10 * * 1,7 which is valid cron and we can check with parseExpression of cron-parser to check if we should run