我们有 scheduled_jobs 的表格,此表格包含以下两列:
重复类型:每周/每两周/每月
开始日期:重复的日期,即如果重复类型是每月,开始日期设置为2015-12-05,则会在每个月的第五天重复。
以下查询是当前正在使用的代码片段:
<?php
foreach(range(1,100) as $num)
{
$numtimestwo = $num * 2;
$query = "SELECT * FROM scheduled_jobs WHERE deleted != TRUE AND ((DATE_ADD(DATE(beginning_date), INTERVAL $num MONTH) = CURDATE() AND repeat_type = 'monthly') OR (DATE_ADD(DATE(beginning_date), INTERVAL $numtimestwo WEEK) = CURDATE() AND repeat_type = 'fortnightly') OR (DATE_ADD(DATE(beginning_date), INTERVAL $num WEEK) = CURDATE() AND repeat_type = 'weekly'))";
// If result is not empty, process the scheduled job
}
?>
但是我注意到了一些问题,这将最终停止工作,因为begin_date变得越来越老,看起来应该有更好的解决方案。
答案 0 :(得分:0)
我使用PHP's diff method解决了DateTime对象的问题。
以下函数采用$ type(“每日/每周/每两周/每月/六个月/每年”)和$ beginning_date(日期字符串)。
例如。如果您的日期为“2010-01-01”,类型为“每月”,那么您希望在每个月的第一天返回true,这将有效。具有“每周”类型的日期“2015-06-05”将在该日期之后每7天返回一次。
function checkInterval($type, $beginning_date)
{
// Get DateTime for today, and DateTime object for $beginngin_date input
$today = date("Y-m-d");
$today = new DateTime($today);
$beginning_date = new DateTime($beginning_date);
// Diff the two dates, and get the save variables for the difference in days, months, years, as well as total days passed ($interval->days)
$interval = $beginning_date->diff($today);
$difference_d = $interval->d;
$difference_m = $interval->m;
$difference_y = $interval->y;
$difference_total = $interval->days;
// If beginning date is today, do not proceed
if($difference_total < 1)
{
return false;
}
// If daily, return true all days
if($type == "daily")
{
return true;
// If weekly, Return true on the day difference being a multiple of 7 days or 0
} else if($type == "weekly") {
if($difference_d == "7" || $difference_d == "14" || $difference_d == "21" || $difference_d == "28" || $difference_d == "0")
{
return true;
}
// If fortnightly, Return true on the day difference between a multiple of 14 days or 0
} else if ($type == "fortnightly") {
if($difference_d == "14" || $difference_d == "28" || $difference_d == "0")
{
return true;
}
// If monthly, only return true when it is same day every month (0)
} else if ($type == "monthly") {
if($difference_d === 0)
{
return true;
}
// If biannually, return true when there's a 6 month difference, and it's the same day of the month
} else if ($type == "six months") {
if($difference_m == "6" && $difference_d == "0")
{
return true;
}
// Return true when year difference is greater than 0, and day and month are equal (0)
} else if ($type == "yearly") {
if($difference_d == "0" && $difference_m == "0" && $difference_y > 0)
{
return true;
}
// Else no matches, return false
} else {
return false;
}
return false;
}