I'm working on a webpage for my home automation system, which will control my garden sprinklers. I already have a scheduled timer setup, and now I'd like to add a countdown timer (turn on for x minutes).
I want to be able to close the webpage, and have the timer continue in the background. When the timer finishes, I want it to do something the instant it reaches zero, even if no webpage is open.
With this in mind, my limited knowledge of webpages tells me the timer should run on the server (in my case Appache2 on an RPi). I have tried this basic example, which works in some ways, but doesn't stop at zero per se.
I changed it slightly to show this issue:
<?php
session_start();
if (!isset($_SESSION['countdown'])) {
$_SESSION['countdown'] = 10;
$_SESSION['time_started'] = time();
}
$now = time();
$timeSince = $now - $_SESSION['time_started'];
$remainingSeconds = ($_SESSION['countdown'] - $timeSince);
echo "Time remaining: $remainingSeconds seconds";
if ($remainingSeconds < 1) {
echo "DONE";
session_destroy();
}
?>
Starting the script, the webpage shows "Time remaining: 10 seconds". Perfect. Upon refresh after 5 seconds, it shows "Time remaining: 5 seconds". Again, perfect. However, if I then wait ten seconds, and refresh, it says "Time remaining: -5 secondsDONE". A clear indication that the script only runs upon page refresh, which makes sense of course.
So what I am looking for is a countdown timer that:
- Runs on the server;
- Can fire an event when reaching zero;
- Can be started, paused, stopped and read from javascript or jQuery.
I'm not looking for a solution in any specific language, as long as it works, I'm happy. The PHP example was just something I stumbled upon while researching the options for what I'm trying to achieve.
Is something like this possible?