2017-07-27 51 views
0

我正在運行一個hearbeat文件,以從我的管理儀表板動態添加/刪除cronjob命令。PHP心跳(cronjob標籤)

我在一個表中保存的命令是這樣的:

+---------------+-------+------+-------------------+---------------+ 
| cronjob_id | hour | min | command   | output  | 
+---------------+-------+------+-------------------+---------------+ 
| 1    | *  | * | /mail.php   | /mail.log  | 
| 2    | 00 | 00 | /update.php  | /update.log | 
+---------------+-------+------+-------------------+---------------+ 

我的心跳文件:

/** 
* create a timeset 
*/ 

$hour = date('H'); 

$minute = date('i'); 

/** 
* select all the commands 
*/ 

$stmt = $db->prepare("SELECT hour,minute,command,output FROM cronjobs"); 

$stmt->execute(); 

$result = $stmt->get_result(); 

while($row = $result->fetch_assoc()){ 

    include_once(ROOT.$row['command']); 

    error_log("Command: ".$row['command']." executed\n",3,ROOT.$row['output']); 

}; 

$stmt->close(); 

正如你所看到的,命令/mail.php應執行每分鐘和命令/update.php應執行每天在00:00(午夜)。我怎樣才能在我的心跳文件中編碼?

回答

0

我想你會想在表格中添加一個日期類型last_run列,然後評估自那時以來的小時數&分鐘,並在需要時執行並使用當前日期時間更新last_run列。

使用現有庫中的下一次任務應該像這樣的運行評價:https://github.com/mtdowling/cron-expression

以下是未經測試的代碼,因爲我不知道庫,但希望將讓你更接近的解決方案:

while ($row = $result->fetch_assoc()) { 
    if (command_should_execute($row)) { 
     include_once(ROOT.$row['command']); 

     error_log(
      sprintf('Command: %s executed\n', $row['command']), 
      3, 
      ROOT.$row['output'] 
     ); 

     // UPDATE last_run COLUMN HERE 
    } 
}; 

function command_should_execute($commandArray) 
{ 
    $cronExpression = $commandArray['minute'] . ' ' . $commandArray['hour']; 
    $cron = Cron\CronExpression::factory($cronExpression); 
    $nextRun = $cron 
     ->getNextRunDate($commandArray['last_run']) 
     ->format('Y-m-d H:i:s'); 

    return (strtotime($nextRun) < time()); 
}