2

我有一个网站,允许用户选择测试脚本,提交所需的测试后,它将发布到 insert.php 并且:

  1. 它在 done=0 (insert.php) 中将一行插入到 MySQL 数据库中。

  2. 有一个侦听器脚本(testexe.php),我想在网络服务器上连续运行(可能休眠 10 秒)并在有 done=0 的行时侦听,执行它们然后更改 done=1,然后继续下一个。

我有这个脚本在一个while循环中运行,但是,我有一个问题,最初如何调用这个php脚本?或者我怎样才能激活它来最初启动?php testexe.php在提交测试之前,我是否必须先在服务器上运行它?因为我知道这个脚本只是监听事件,在我的情况下,事件完成 = 0,但是我怎样才能让这个脚本一直运行(系统启动)?我不太明白这部分。

我想这样做的原因是因为可能有多个用户同时发送请求,所以我想确保他们一个一个地处理测试并将它们排队。

测试程序文件

<?php

...
...    

//while there are still jobs that are not done..
while (1) {
    //wait for 10 seconds and query again...
    sleep(10);
    $statusResult = mysqli_query($dbConnection, $qStatus);
    //if there are undone jobs we pick them and execute them
    if (mysqli_num_rows($statusResult) > 0){
        //query the next undone test case
        $testResult = mysqli_query($dbConnection, $qNextTest);

        //fetch the returned query object and store needed parameters 
        $row = $testResult->fetch_assoc();
        $id = $row['id'];               
        $test_script = $row['test_script']; 
        $gateway = $row['gateway'];         


        if ($connection = @ssh2_connect($gateway, 22)) {
            ssh2_auth_password($connection, $user, $password);

            //execute the test case
            $stream = ssh2_exec($connection, "/my/path/to/script.sh"); 

            //fetch output stream and stderr
            stream_set_blocking($stream, true);
            $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
            $stream_err = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
            while($line = fgets($stream_out)) {flush(); echo '<pre>' . $line . '</pre>';}               
            echo '<pre>' . "------------------------\n" . '</pre>';
            while($line = fgets($stream_err)) {flush(); echo '<pre>' . $line . '</pre>';}
            fclose($stream);    

            //update the table after the above script is done
            $qUpdateStatus = "UPDATE table SET status = 1 WHERE id = $id";
            $updateresult = mysqli_query($dbConnection, $qUpdateStatus);
        }

    }
}

?>
4

2 回答 2

1

我可以想到两个选项:(1)在您的网络服务器上创建一个每 5 分钟调用一次 testexe.php 的 cron 作业,或者(2)让 POST 执行 testexe.php 脚本,并注意 testexe.php 检查是否有另一个testexe.php 的实例当前正在运行。

于 2017-09-19T17:04:04.957 回答
1

如果你使用 Linuxcron可能适合你:

将此行添加到您的 crontab 文件中(通过 访问crontab -e

10   *   *   *   *   php testexe.php

然后删除 while 循环和 sleep 语句。

如果您需要 10 秒以外的时间,此页面可能会对您有所帮助:http ://www.crontabgenerator.com/

于 2017-09-19T17:05:00.213 回答