2017-05-30 87 views
0

我有一個cron作業,從數據庫獲取結果以檢查用戶設置的時間間隔是否落在今天的日期。我目前正在考慮如下:計算任務的頻率間隔

  1. 獲取該行的時間列。例如:2017-05-25 00:00:00
  2. 獲取頻率設置。例如:每2周。
  3. 以上述格式獲取當前日期。例如:2017-05-31 00:00:00
  4. 獲得天之差。例如:6天。
  5. 將頻率設置爲天。例如:2周= 14天;
  6. 劃分(時間差(天))(以天數爲單位)。例如:6/14

這樣我只會在設定的時間過去2周後纔會得到結果。即,14/14,28/14,42/14,...

如果頻率是在幾個月內,我可以開始除以30.但不知何故,這感覺像一個哈克的做法。所以我的問題是,如果有更好的方法來做這個計算來檢查差異。

這就是我所做的,正如上面例子所解釋的那樣。

` $frequency = ; // Get the relevant fields from db 
    $today = date(Y-m-d H:i:s); 
    foreach ($frequency as $key => $value) { 
     $frequency_in_days; 
     $frequency_type = $value->type; 
     $frequency_repeat = $value->repeat; 

     if($frequency_type == 1){ 
     $frequency_in_days = $frequency_repeat; 
     } elseif($frequency_type == 2) { 
     $frequency_in_days = $frequency_repeat * 7; 
     } elseif($frequency_type == 3) { 
     $frequency_in_days = $frequency_repeat * 30; 
     } elseif($frequency_type == 4) { 
     $frequency_in_days = $frequency_repeat * 365; 
     } 

     // Get number of days spent between start_date and today in days. 
     $interval = date_diff($value->start_date, $today)->format('%a'); 
     $result = $interval % $frequency_in_days; 

     if ($result == 0) { 
     // Frequency falls today! Do the job. 
     } 
    }` 

注意:cron作業運行此腳本。腳本再次需要檢查今天是否屬於頻率設置。

也是爲了論證的緣故,這是計算差異的最佳邏輯嗎?

謝謝。

+0

你有任何代碼後

SELECT * FROM schedule WHERE TIMESTAMPDIFF(last_run, NOW()) >= frequency_seconds 

?記錄集中行的格式?第一點是什麼日期?最後一件事發生了? 我認爲你應該對你的問題進行一些改寫,使其更清晰,更少關閉。 https://stackoverflow.com/help/mcve – Eineki

+0

我添加了代碼。我之前沒有添加任何代碼,因爲我認爲問題陳述足夠解釋了。謝謝你指出。 –

+0

我刪除了我的問題,因爲'這個數據庫有成千上萬的記錄',而在原始問題中,你通過循環記錄 – Peter

回答

0

這將工作

Table "schedule" 
`last_run` timestamp, 
`frequency_seconds` int 

例如查詢應該去每兩週任務:獲取行更新last_runNOW()