2017-07-27 89 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()); 
}