Setting up a fortnightly cron event with date-fns
Cron is a powerful automation tool for scheduling tasks.
However I recently discovered that scheduling operations that should take place on a fortnightly or ‘bi-monthly’ basis isn’t possible with standard cron expressions.
As part of a recent project I was asked to schedule an email to occur every other Wednesday at 12.00pm and found out this was not achievable with cron. I found some convoluted solutions on Stackoverflow but ended up using a more simple solution.
Cron can most definitely schedule a weekly event at a given time - so let’s start with that as a basis, then use some more code to achieve the desired fortnightly method call (see this article for a simple boilerplate for setting up cron in your Node.js projects).
Since I was already using date-fns
in my project I made use of its getWeek()
method.
Calling getWeek(new Date())
returns the number value of the current week and with a simple helper function, we can check if the current week is odd or even, and then we can make our task run every 2 weeks.
In my scenario the client wanted to schedule a fortnightly mail to all users, which was to begin the following week… which was an even number. so I used the condition that if the week was not even, then simply return out of the function (until next week).
Here’s the code:
import { getWeek } from 'date-fns';
function isEven(n) {
return n % 2 == 0;
}
function doMail() {
const weekNumber = getWeek(new Date());
if (!isEven(weekNumber)) {
// we only want to send email every fortnight, cron does not allow for fortnightly intervals therefore we use this func to only fire the mail on odd or even weeks
console.log('week not even, do not send this week');
return;
}
// Send email
}