1

I am running this via the command line. When the loop is running, is there any way I can pause the execution of the code? Ideal case would be that I could press a key to pause and then another key to resume. If I don't press the pause key then the loop continues until $i == 1000

<?php

echo "How long should the code sleep between increments?\n";
echo ">> ";

$sleep = trim(fgets(STDIN));

for ($i = 1; $i <= 1000; $i++) {
    echo "$i\n";
    sleep($sleep);
}

This is a heavily simplified example of my actual need for the code.

Chris
  • 4,672
  • 13
  • 52
  • 93
  • http://php.net/manual/en/features.commandline.php#94924 – mwweb Sep 10 '17 at 22:12
  • 1
    is php really the right language for this? –  Sep 10 '17 at 22:21
  • @rtfm, nothing wrong with PHP for cli, even though it was designed for web, it has nearly all the same libraries and functionality available as any interpreted language. – Devon Bessemer Sep 10 '17 at 23:03
  • Possible duplicate of [PHP CLI: How to read a single character of input from the TTY (without waiting for the enter key)?](https://stackoverflow.com/questions/3684367/php-cli-how-to-read-a-single-character-of-input-from-the-tty-without-waiting-f) – Devon Bessemer Sep 10 '17 at 23:06
  • if having to run a while loop to wait for a keyboard input does not scream wrong language, i dont know what does –  Sep 10 '17 at 23:25

1 Answers1

2

I don't sure my code is best solution or not but it work.

function checkResume()
{
    $r = false;

    while (!$r) {
        if (fgets(STDIN) == "r") {
            $r = true;
        }
    }

}

function checkPause()
{
    $input = fgets(STDIN);
    if (!empty($input) && $input == "p") {
        return true;
    }
    return false; 
}

echo "How long should the code sleep between increments?\n";
echo ">> ";

$sleep = trim(fgets(STDIN));

echo "\nStart ...\n";

stream_set_blocking(STDIN, false);
for ($i = 1; $i <= 1000; $i++) {
    if (checkPause()) {
        echo "wait for resume \n";
        checkResume();
    }

    echo "$i\n";
    sleep($sleep);
}

Hope this help.