breejs / later

*Maintained fork of Later.* A javascript library for defining recurring schedules and calculating future (or past) occurrences for them. Includes support for using English phrases and Cron schedules. Works in Node and in the browser.
https://breejs.github.io/later/
MIT License
134 stars 13 forks source link

[feat] on the first Monday of the month #30

Closed sbrunner closed 1 year ago

sbrunner commented 1 year ago

What problem are you trying to solve?

I can't run a job every month on a specific day of the week.

Describe the feature

Be able to run a job every month on a specific day of the week.

Checklist

titanism commented 1 year ago

You can use dayjs to make this easy. Make a job run daily at whatever time you want. See Bree docs for how to configure a schedule for a job. This job would return early if it was not the first Monday of the month (or in the example below, the code only executes if it is the first Monday). Pretty simple and readable code.

const { parentPort } = require('worker_threads');

const dayjs = require('dayjs');

(async () => {
  const firstMonday = dayjs().startOf('month').add('6', 'day').startOf('isoWeek').toDate();
  const today = dayjs().startOf('day').toDate();

  // today was the first monday of the month so we can run our code
  if (firstMonday.getTime() === today.getTime()) {
    // your code here
  }

  // signal to parent that the job is done
  if (parentPort) parentPort.postMessage('done');
  else process.exit(0);
})();

Further proof this works:

> for (let i = 1; i <= 12; i++) { console.log(dayjs().subtract(i, 'month').startOf('month').add('6', 'day').startOf('isoWeek').format('dddd M/D/YY')) }
Monday 11/7/22
Monday 10/3/22
Monday 9/5/22
Monday 8/1/22
Monday 7/4/22
Monday 6/6/22
Monday 5/2/22
Monday 4/4/22
Monday 3/7/22
Monday 2/7/22
Monday 1/3/22
Monday 12/6/21