Today, on a Linux mailing list, someone asked how to run a cron job every 4th Monday of the month. We didn't find a way to do it yet with crontab (day-of-week and day-of-month fields are ORed together..), so I wrote a perl script to check if today is the 4th Monday (or generally the nth Weekday) of the month and, if so, exit sucessfully. For example, put a cron entry to run every Monday, and then something like:
4 15 * * 1 /some/path/is_nth_weekday.pl && /your/path/yourscript
#!/usr/local/bin/perl -w # is_nth_weekday.pl -- exit successfully if today is the # nth weekday of the month (e.g. 4th Monday) use strict; use Date::Manip; my ($today, $month, $year, $nth_weekday, $today_date, $nth_weekday_date, $which, $day); $which = $ARGV[0] || '4th'; $day = $ARGV[1] || 'monday'; # get today's datetime $today = ParseDate('today'); # get today's month and year to find $nth_weekday ($month, $year) = UnixDate($today, '%B', '%Y'); # get nth Weekday's datetime $nth_weekday = ParseDate("$which $day in $month $year"); # get today's date $today_date = UnixDate($today, '%Y%m%d'); # get nth Weekday's date $nth_weekday_date = UnixDate($nth_weekday, '%Y%m%d'); # is today the nth Weekday? if ($today_date eq $nth_weekday_date) { exit 0; } else { exit 1; }

In reply to cron: every nth week by kwoff

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.