perl:将当前时间与特定时间比较
我是Perl的新手。我正在制作每天运行的脚本。我想检查当前时间不到特定时间。我当前的解决方案是我从localtime
中提取小时
min ,然后对其进行比较。但是有人告诉我找到一个更好的解决方案。
当前代码:
my $flag;
for (;;) {
$flag = GetValue();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
if( $flag ) {
#do action here
last;
} elsif ( $hour <= 17 ) {
if( $min <=30 ) {
print STDOUT "Keep running till 17:30 \n";
sleep 300;
} else {
die "Error";
}
} else {
die "Error";
}
}
基本上,语句$ flag = getValue();
有时会意外返回未定义的值,并导致脚本失败。因此,我们想检查$标志是否定义。如果定义了它,则我们执行一些代码并退出for循环。否则我们检查时间。如果时间少于17:30,那么我们要等待一段时间,然后尝试再次获得标志的价值。我只需要更改将当前时间比较17:30的逻辑
我想要我的东西:
} elsif ( $current_time <= 17:30 ) {
print STDOUT "Keep running till 17:30 \n";
sleep 300;
}
如何实现这一目标?
I am very new to perl. I am working on a script that runs everyday. I want to check that current time is less than a specific time. My current solution is that I extract hour
and min
from localtime
and then compare it. But I was told to find a better solution.
Current code:
my $flag;
for (;;) {
$flag = GetValue();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
if( $flag ) {
#do action here
last;
} elsif ( $hour <= 17 ) {
if( $min <=30 ) {
print STDOUT "Keep running till 17:30 \n";
sleep 300;
} else {
die "Error";
}
} else {
die "Error";
}
}
Basically, the statement $flag = GetValue();
sometimes returns undefined value unexpectedly and causes the script to fail. So we want to check if $flag defined. If it is defined then we execute some code and exit the for loop. Else we check the time. If the time is less that 17:30 then we want to wait for some time and try to get the value of flag again. I only need to change the logic of comparing current time to 17:30
I want my something like:
} elsif ( $current_time <= 17:30 ) {
print STDOUT "Keep running till 17:30 \n";
sleep 300;
}
How do I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
处理日期时间的好方法是使用一个好的库,例如 dateTime
避免为每个比较构建一个新对象,但这会使代码更加复杂。请注意,
DateTime
是一个大型库,这可能是一个过度的库。如果目的确实是仅仅将当前时间与固定小时的时间进行比较,那么也许
足够好了吗?
或形式和使用可以通过陈述目的进行词汇进行比较的字符串,
这样做
可能更清晰,并且直接指示
localtime
的返回的哪些部分。也可以忽略
时间
,per localtimeThe good and solid way to deal with date-times is to use a good library, like DateTime
One can avoid constructing a new object for every comparison but that would make the code more complicated. Note that
DateTime
is a large library and this could be an overkill.If the purpose is indeed to merely compare the current time to a fixed hour-minute then perhaps
is good enough?
Or form and use strings that can be lexically compared
For the stated purpose it is fine to do
This may be clearer as well as it directly indicates which parts of
localtime
's return are used.Can also leave out
time
, per localtime