From 204932bfeb82b7b3032ed90a1e85b9b07e854c47 Mon Sep 17 00:00:00 2001 From: Christian Hofmaier Date: Tue, 22 Dec 2020 17:02:21 +0100 Subject: [rebootcontrol] calculate next execution time function --- .../rebootcontrol/inc/scheduler.inc.php | 35 +++++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/modules-available/rebootcontrol/inc/scheduler.inc.php b/modules-available/rebootcontrol/inc/scheduler.inc.php index 0776885d..27a22646 100644 --- a/modules-available/rebootcontrol/inc/scheduler.inc.php +++ b/modules-available/rebootcontrol/inc/scheduler.inc.php @@ -8,7 +8,7 @@ class Scheduler self::deleteSchedule($locationid, $action); return false; } - $nextexec = self::calcNextexec($action, $openingTimes); + $nextexec = self::calcNextexec($action, $options, $openingTimes); $json_options = json_encode($options); self::upsert($locationid, $action, $nextexec, $json_options); return true; @@ -22,11 +22,38 @@ class Scheduler )); } - private static function calcNextexec($action, $openingTimes) { - //TODO: Calculate nextExec based on openingTimes. Needs action to know if openTimes or closingTimes are used. - return 0; + private static function calcNextexec($action, $options, $openingTimes) { + $openingTimes = json_decode($openingTimes, true); + $now = time(); $times = []; + foreach ($openingTimes as $row) { + // Fetch hour and minutes of opening / closing time. + $hourmin = explode(':', ($action == 'wol' ? $row['openingtime'] : $row['closingtime'])); + // Calculate time based on offset. + $min = ($action == 'wol' ? $hourmin[0] * 60 + $hourmin[1] - $options['wol-offset'] : $hourmin[0] * 60 + $hourmin[1] + $options['sd-offset']); + // Calculate opening / closing time of each day. + foreach ($row['days'] as $day) { + $next = strtotime(date('Y-m-d H:i', strtotime($day . ' ' . $min . ' minutes'))); + if ($next < $now) { + $times[] = strtotime(date('Y-m-d H:i', strtotime('next '.$day . ' ' . $min . ' minutes'))); + } else { + $times[] = $next; + } + } + } + // Iterate over days, use timestamp with smallest difference to now. + $res = 0; $smallestDiff = 0; + foreach ($times as $time) { + $diff = $time - $now; + if ($res == 0 || $diff < $smallestDiff) { + $smallestDiff = $diff; + $res = $time; + } + } + return $res; } + + private static function upsert($locationid, $action, $nextexec, $options) { $schedule = Database::queryFirst("SELECT locationid, action FROM `reboot_scheduler` -- cgit v1.2.3-55-g7522