[英]Most effective way to determine if a datetime is within a time frame
I have a cronjob, that kicks in every 5 minutes. 我有一个cronjob,每5分钟踢一次。 It should do some tasks only at specific times of the day (eg morning and evening). 它应该仅在一天的特定时间(例如,早上和晚上)执行某些任务。
What's php's most effective / elegant way to determine if the DateTime of now is in between the 5 minute time frame in that the cronjob may kick in? 什么是php最有效/最优雅的方法来确定now的DateTime是否在5分钟的时间范围内,以使cronjob起作用?
At the moment I'm doing: 目前,我正在做:
$date = new DateTime();
$hour = (int)$date->format('H');
$min = (int)$date->format('i');
if($hour == 7 && ($min >= 40 || $min < 45)) {
// Do something in the morning
}
if($hour == 21 && ($min >= 00 && $min < 05)) {
// Do something in the evening
}
But this seems like a lot of code. 但这似乎是很多代码。 Ain't there something like 那里没有像
$date->isInTimeRane($begin, $end);
as native php code? 作为本地PHP代码?
If $begin
and $end
are of type DateTime as well, you can simply use them like this: 如果$begin
和$end
也属于DateTime类型,则可以像这样简单地使用它们:
if ($begin <= $date && $date <= $end) {
// .. date is within the range from $begin -> $end ..
To address your specific problem, how about this (quite elegant) function: 为了解决您的特定问题,如何使用此功能(非常优雅):
function isWithinTimerange($hours, $minutes, $timerangeInMinutes = 5) {
$now = new DateTime();
$begin = clone $now;
$begin->setTime($hours, $minutes);
$end = clone $begin;
$end->modify('+'. intval($timerangeInMinutes) .' minutes');
return ($begin <= $now && $now < $end);
}
if (isWithinTimerange(7, 40)) {
// ...
You can extend DateTime to add your own methods to it. 您可以扩展DateTime以向其中添加自己的方法。 I would do it this way:- 我会这样:-
class MyDateTime extends DateTime
{
/**
* Checks if this DateTime is between two others
* @param DateTime $start
* @param DateTime $end
* @return boolean
*/
public function inRange(DateTime $start, DateTime $end){
return ($this >= $start && $this <= $end);
}
}
Then you can simply do:- 然后,您可以简单地做:
$begin = new DateTime($sometime);
$end = new DateTime($someLaterTime);
$myTime = new MyDateTime($yetAnotherTime);
var_dump($myTime->inRange($begin, $end);
That is the cleanest way I can think of of doing it and pretty much what you asked for. 这是我想到的最干净的方法,几乎可以满足您的要求。
You can use the UNIX time instead (seconds since Jan,1,1970 aka Epoch). 您可以改用UNIX时间(从1970年1月1日开始,以秒为单位)。 Then logic should be something like the following. 那么逻辑应该类似于以下内容。
<?php
$current_time = time(); //Get timestamp
$cron_time = (int) ;// Time cron job runs (you can use strtotime() here)
$five_minutes = 300; //Five minutes are 300 seconds
if($current_time > $cron_time && $current_time - $cron_time >= $five_minutes) {
echo "Cron Job is too late";
} elseif($current_time >= $cron_time && $five_minutes >= $current_time - $cron_time){
echo "Cron Job ran within time frame";
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.