我有一个让用户选择测试脚本的网站,并且在提交了所需的测试后,它将发布到insert.php和:
-
它插入在done = 0(insert.php)的MySQL数据库中发送一行。
-
我想在Web服务器上连续运行(也许睡10秒)并在有DONE = 0的行时收听,然后聆听,然后执行它们,然后更改DOMON =1,然后转到下一个。
我有一段时间内运行此脚本,但是,我有一个问题,最初如何称呼此PHP脚本?还是如何将其激活以最初启动?在提交测试之前,我是否必须先在服务器上像php testexe.php
一样运行它?因为我知道这个脚本只会收听事件,就事件完成了= 0,但是如何保持此脚本一直运行(系统启动)?我不太明白这部分。
我想这样做的原因是因为可能会有多个用户同时发送请求,因此我想确保他们一一处理测试并排队。
testexe.php
<?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);
}
}
}
?>
如果使用Linux cron
可能适合您:
将此行添加到您的crontab文件(通过crontab -e
访问)
10 * * * * php testexe.php
然后删除WARE循环和睡眠语句。
如果您需要10秒以外的其他内容,此页面可能会帮助您:http://www.crontabgenerator.com/
我可以想到两个选项:(1)在您的Web服务器上创建一个CRON作业,该作业每〜5分钟调用Testexe.php,或(2)让帖子执行testexe.php带有警告的脚本testexe.php检查testexe.php当前是否正在运行的另一个实例。