[Perl] スケジュールスイッチ用関数

Posted by
ぴろり
Posted at
2006/08/21 23:34
Post Comment
コメントできます
Category
開発メモ カテゴリ

 バッチスクリプトでは、何時〜何時の間だけ実行する/しない、といった制御が必要になる場合があります。この判定を簡単に行うための小さな Perl 関数です。Perl スクリプトの自動運転などで活躍するつもり。

このエントリーをはてなブックマークに追加  

#!/usr/bin/perl
use strict;

### Schedule (From) <= T < (To)
my %schedule = (
	'21:00:00-27:00:00' => 1,
	'23:00:00-25:00:00' => 0,
);
use Data::Dumper;
print Dumper (%schedule);

&testcase ('20:00:00');
&testcase ('21:00:00');
&testcase ('22:00:00');
&testcase ('22:59:59');
&testcase ('23:00:00');
&testcase ('24:00:00');
&testcase ('00:00:00');
&testcase ('00:59:59');
&testcase ('25:00:00');
&testcase ('01:00:00');
&testcase ('26:00:00');
&testcase ('02:00:00');
&testcase ('02:59:59');
&testcase ('03:00:00');

sub testcase {
	my ($item) = @_;
	printf "%s : %s
", $item, &isScheduledOn ($item) ? 'OK' : 'NG';
}



###
sub isScheduledOn {
	my ($curtime) = @_;
;#
	return undef unless $curtime =~ m/s*(d+)s*:s*(d+)s*:s*(d+)s*/;
	my ($hc,$mc,$sc) = ($1,$2,$3);
;#
	my $ret = 0;
	foreach (keys %schedule) {
		my $switch = $schedule{$_};
		;# parse
		next unless m/s*(d+)s*:s*(d+)s*:s*(d+)s*-?s*(d+)s*:s*(d+)s*:s*(d+)s*/;
		my ($h1,$m1,$s1, $h2,$m2,$s2) = ($1,$2,$3, $4,$5,$6);
		;# normalize; h:[00,23], m:[00,59], s:[00,59]
		($m1++, $s1 -= 60) while 60 <= $s1; ($h1++, $m1 -= 60) while 60 <= $m1; ($h1 -= 24) while 24 <= $h1;
		($m2++, $s2 -= 60) while 60 <= $s2; ($h2++, $m2 -= 60) while 60 <= $m2; ($h2 -= 24) while 24 <= $h2;
		;# T1 must be < T2
		($h2 += 24) while _ti($h2,$m2,$s2) < _ti($h1,$m1,$s1);

		;# Check on today and tomorrow
		my $_tic = _ti($hc,$mc,$sc);
		foreach (0..1) {
			if (_ti($h1,$m1,$s1) <= $_tic && $_tic < _ti($h2,$m2,$s2)) {
				return 0
					unless $switch;
				$ret = 1;
			}
			$_tic += 24 * 60 * 60;# tomorrow
		}
	}
	return $ret;
#
	sub _ti { ($_[0] * 60 + $_[1]) * 60 + $_[2] }
}

実行結果の例

X:temp>perl schedule.pl
$VAR1 = {
          '21:00:00-27:00:00' => 1,
          '23:00:00-25:00:00' => 0
        };
20:00:00 : NG
21:00:00 : OK
22:00:00 : OK
22:59:59 : OK
23:00:00 : NG
24:00:00 : NG
00:00:00 : NG
00:59:59 : NG
25:00:00 : OK
01:00:00 : OK
26:00:00 : OK
02:00:00 : OK
02:59:59 : OK
03:00:00 : NG
このエントリーをはてなブックマークに追加  



コメントを投稿する

 
 (必須, 匿名可, 公開, トリップが使えます)
 (必須, 匿名可, 非公開, Gravatar に対応しています)
 (必須)
スパム コメント防止のため「投稿確認」欄に ランダムな数字 CAPTCHAについて を入力してから送信してください。お手数ですがご協力のほど宜しくお願いいたします。