0

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?

Timmiej93
  • 1,328
  • 1
  • 16
  • 35
  • well, not really ... PHP preprocesses your code, and sends it to the browser - it's not an interactive relationship between PHP and browser – Jaromanda X Jul 24 '18 at 12:20
  • Maybe I should've added that I'm not looking for a php specific solution. Like I said, I'm very new to everything webpage related, so this was just the first thing that came to my mind. Any language will work for me. – Timmiej93 Jul 24 '18 at 12:22
  • ok, replace "PHP" in my comment with "server side code" – Jaromanda X Jul 24 '18 at 12:23
  • You can store the scheduled date/time in a database, then run a script (any language, could be PHP CLI) every minute as a cron job on the server which checks if the time has passed and triggers the desired action. You can read the same database from PHP to show the time remaining in a browser. – DarthJDG Jul 24 '18 at 14:26

3 Answers3

1
//here is the solution you can check   
<?php
if (isset($_POST['submit'])){
$time = $_POST['time'];
?>
< div id="countdown"></div>
<script type="text/javascript">
    var iTime = <?php echo $time; ?>;
    function countdown()
    {                
        var i = setInterval(function(){
            document.getElementById("countdown").innerHTML = iTime;
            if(iTime==0){
                alert('Countdown timer finished!');
                clearInterval(i);
            } else {
                iTime--;
            }                   
        },1000);                        
    }           
    countdown();
</script>
<?php
        } else {
       ?>
         <form name="test" method="post">
             Enter time: <input type="text" name="time" />
             <input type="submit" name="submit" value="Submit" />
          </form>        
      <?php
     }
        ?>
Rj Adii
  • 36
  • 4
1

Your script runs only when a request arrives to process.

It means:

  • When you start, it runs once, and sets the session's values.

  • It runs once, when you refresh the page after 5 seconds, and writes, 5 seconds is remaining.

  • It runs once, when you refresh the page after another 10 seconds, and this time the countdown is elapsed. so it writes 'DONE'.

But PHP does nothing among these refreshes.

Focus on the problem: You want to start a process, when you open the web page (you send a request to the server), and you want the process to stop after a specified time.

It is difficult with PHP, because it cannot perform scheduled tasks. You can use sleep() method to set a delay, but in this case the web page will not get any response until the whole process is finished (turn on the sprinklers, and after X seconds turn off the sprinklers). And even the delay is too long (longer than 30 second by default), the PHP exits with an error. (Max run time can be set with set_time_limit() method, so it is not a big problem.)

Personally recommend to use Java, because it is able to perform scheduled tasks, or use big delays, but I think the Java language is much more difficult to learn than PHP.

Saphyra
  • 450
  • 3
  • 15
  • Luckily, I already know Java, so that shouldn't be a problem. I'll look into running a java file on the server, and I'll report back if I run into any issues. Thank you for your suggestion. – Timmiej93 Jul 24 '18 at 16:36
  • I may need some assistance in getting Java running on a server. I can't really find anything about server side java. Do you have any info to point me in the right direction? – Timmiej93 Jul 25 '18 at 18:39
  • [link](https://spring.io/guides/gs/serving-web-content/) maybe this can help. Spring Boot helps a lot! – Saphyra Jul 26 '18 at 06:36
-1

Please first search then ask a question

PHP server side timer

<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
  file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;

if($difference <= 0)
{
  echo 'time is up, BOOOOOOM';
  // execute your function here
  // reset timer by writing new timestamp into file
  file_put_contents($timestamp_file, time()+$timer);
}
else
{
  echo $difference.'s left...';
}
?>
zani
  • 88
  • 9
  • Still requires user interaction to run the code. (I mean this will not turn off the sprinklers automatically when the countdown reaches zero, only when the user reloads the page) – Saphyra Jul 24 '18 at 13:29
  • https://stackoverflow.com/questions/6755940/using-javascript-countdown-with-server-side-time – zani Jul 24 '18 at 13:47
  • I did search before I posted, as I clearly stated in my question. I also found the question you linked, but it does exactly the same as the example I found and provided in my question, which is not enough for what I need. – Timmiej93 Jul 24 '18 at 16:34