2017-07-27 9 views
0

私は、管理ダッシュボードから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列を現在の日時で更新したいと思うでしょう。

タスクはこの1つのように実行されなければならない次の時間を評価するために、既存のライブラリを使用してください:私は、ライブラリを知らないが、うまくいけば近いソリューションにあなたを取得しますので、次の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()); 
}