Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

cron: every nth week

by kwoff (Friar)
on Jan 01, 2002 at 02:16 UTC ( #135446=snippet: print w/replies, xml ) Need Help??
Description: 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;
}
Replies are listed 'Best First'.
Re: cron: every nth week
by runrig (Abbot) on Jan 01, 2002 at 02:57 UTC
    If you're scheduling the script to run every Monday (and only on Monday, or whatever day you're after), then can just see if its the nth week of the month. Here's a version that doesn't use modules (notice there's no real difference between bad input and a day that's not the nth week):
    my $nth = shift; die "N must be numeric" if $nth =~ /\D/; die "Day is out of range" if $nth > 5; my ($mday) = (localtime)[3]; my $weeks = int(($mday-1)/7)+1; exit 0 if $weeks == $nth; exit 1;
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://135446]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2022-05-25 21:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (90 votes). Check out past polls.

    Notices?