Use of a day-of-week like Mon#2
as suggested in other answers is non-standard and is not implemented by ISC Cron (the Vixie Cron derivative used by most systems, including most Linux distributions and BSDs). It's certainly not in the crontab(5) page for Debian's latest Testing package of cron 3.0pl1-186+b1.
More pertinent to this question, which asks about the Hangfire for C#, the Performing Recurrent Tasks documentation is ambiguous, noting simply that "you can also use CRON expressions to specify a more complex schedule", relying on that Wikipedia link to provide further detail. Digging further, the HangfireIO Cronos project, which I assume is the underlying cron implementation, does in fact note that it supports the non-standard L
, W
, and #
characters.
That means Hangfire users can indeed use 0 8 * * Mon#2
to run at 8a on the second Monday of every month. (Other answers here use a question mark, but HangfireIO's docs say that's synonymous with *
in their implementation, so I see no reason to add another non-standard character.)
Here's a solution without non-standard characters that should work on Posix-style systems like BSD and Linux:
#m h dom mo dow command
0 8 * * Mon d=$(date +\%e) && [ $d -ge 8 ] && [ $d -le 14 ] && echo "2nd Monday"
Since cron can't handle this on its own, we invoke date
to get the day of the month and then ensure it's the 8th through the 14th. We could alternatively have implemented this as 0 8 8-14 * * [ $(date +\%w) = 1 ] && echo "2nd Monday"
, but that cron job runs (and does nothing) six times a month (72 times a year) while this cron job runs (and does nothing) 3-4 times a month (40 times a year), thus polluting your syslog less.
Since Hangfire is C# and probably not run on a Posix-style system, you shouldn't rely on Bash/Posix shell logic or the Posix date
command. This answer is here for completeness since #
is not standard.
Do note that 0 8 8-14 * Mon
will not work because cron sees days of month and days of week as unions rather than intersections; this command will run on any day that is the 8th to the 14 of a month OR any Monday.