I have this little script and function:
function control($value,$position)
{
if ($_SERVER['REMOTE_ADDR']=="".$value."" && $position==0)
{
print "".$value." $x<br>";
return;
}
else
{
control($value,$position);
usleep(20);
}
}
$x=0;
foreach($aa as $aaa)
{
$exp=explode("-",$aaa);
$exp2=explode("_",$exp[1]);
control($exp2[0],$x);
$x++;
}
The loop takes values from a file and sends them to a function to verify, in the function for example if value is the same as the IP of a user it works and if not it continues to execute the function. If not, the idea it repeats to continue verification; the function stops when finally the function verifies this value and it is ok.
I need this to work in one only load, for this I am thinking to use the sleep and repeat functions because the time difference for verification is very low, but in some moments more than 3 users can need to verify this.
The most important for me is to know I can do this in the function because if I use it in this way all the time the page tells me the connection is down, and I only need to repeat the function when the verification result is not the same, and if it is not the same repeat the function another time inside the loop and sleep and repeat in the wait mode.
Sorry but I try to tell all this the best I can.
Regards and thanks.
Related
I am tyring to make a php function that updates every second using php itself no other languages, just pure PHP codes.
function exp(){
//do something
}
I want it to return a value each second. Like update every second.
For an application server (not a web server), best practice is to use an event loop pattern instead of sleep. This gives you the ability to run multiple timers should the need arise (sleep is blocking so nothing else can run in the mean time). Web servers on the other hand should not really be executing any long-running scripts.
Whilst other languages give you event loops out of the box (node / js for example, with setInterval), PHP does not, so you have to either use a well known library or make your own). React PHP is a widely used event loop for PHP.
Here is a quick-and-dirty "hello world" implementation of an event loop
define("INTERVAL", 5 ); // 5 seconds
function runIt() { // Your function to run every 5 seconds
echo "something\n";
}
function checkForStopFlag() { // completely optional
// Logic to check for a program-exit flag
// Could be via socket or file etc.
// Return TRUE to stop.
return false;
}
function start() {
$active = true;
$nextTime = microtime(true) + INTERVAL; // Set initial delay
while($active) {
usleep(1000); // optional, if you want to be considerate
if (microtime(true) >= $nextTime) {
runIt();
$nextTime = microtime(true) + INTERVAL;
}
// Do other stuff (you can have as many other timers as you want)
$active = !checkForStopFlag();
}
}
start();
In the real world you would encapsulate this nicely in class with all the whistles and bells.
Word about threading:
PHP is single threaded under the hood (any OS threading must be manually managed by the programmer which comes with a significant learning curve). So every task in your event loop will hold up the tasks that follow. Node on the other hand, for example manages OS threads under the hood, taking that "worry" away from the programmer (which is a topic of much debate). So when you call setInterval(), the engine will work its magic so that the rest of your javascript will run concurrently.
Quick final note:
It could be argued that this pattern is overkill if all you want to do is have a single function do something every 5 seconds. But in the case where you start needing concurrent timers, sleep() will not be the right tool for the job.
sleep() function is the function that you are looking for:
while (true) {
my_function(); // Call your function
sleep(5);
}
While loop with always true
Call your function inside while loop
Wait for 5 seconds(sleep)
Return the beginning of the loop
By the way it's not a logical use case of endless loops in PHP if you are executing the script through a web protocol(HTTP, HTTPS, etc.) because you will get a timeout. A rational use case could be a periodic database updater or a web crawler.
Such scripts can be executed through command line using php myscript.php or an alternative (but not recommended) way is using set_time_limit to extend the limit if you insist on using a web protocol to execute the script.
function exp(){
//do something
}
while(true){
exp();
sleep(5);
}
Use sleep function to make execution sleep for 5 seconds
it will be better if you use setInterval and use ajax to perform your action
$t0 = microtime(true);
$i = 0;
do{
$dt = round(microtime(true)-$t0);
if($dt!= $i){
$i = $dt;
if(($i % 5) == 0) //every 5 seconds
echo $i.PHP_EOL;
}
}while($dt<10); //max execution time
Suppose exp() is your function
function exp(){
//do something
}
Now we are starting a do-while loop
$status=TRUE;
do {
exp(); // Call your function
sleep(5); //wait for 5 sec for next function call
//you can set $status as FALSE if you want get out of this loop.
//if(somecondition){
// $status=FALSE:
//}
} while($status==TRUE); //loop will run infinite
I hope this one helps :)
It's not preferable to make this in PHP, try to make on client side by calculating difference between time you got from database and current time.
you can make this in JS like this:
setInterval(function(){
// method to be executed;
},5000); // run every 5 seconds
I have a PHP script which will run 24/7 on a VPS with an infinite loop, but problem is that how can I break the infinite loop in php script when desired in order so that the script exists properly?
I know I can kill the process, but if I kill then script will stop immediately
and my loop size is very big and if at time of killing the process the execution of is somewhere in middle of loop then the rest half of loop would not be executed and it will create bugs. Also I have some code after loop so if process gets killed then that code would not be executed.
So my question is that how to break a infinite loop of a PHP script running in background when desired without killing the process?
Instead of:
while(true) {
Do:
while(!file_exists("KILL")) {
Then, when you want to kill the script, simply create the KILL file. You could make it easier for yourself by having a kill.php script that just creates that file for you, so you don't have to remember exactly what to do.
Personally I find PHP scripts easier to work with over EXEs for console apps, but that's just opinion.
Q1. Windows Task Scheduler.. don't insert any loop, just insert CGI directory,then create time.
Q2. PHP would be alot better if you ask me.
although, It's not about Performance.
Sounds like you're coding a server, take a look at this, hope it helps.
<?php
class ServerManager
{
private $serverState;
public function process()
{
if(!$this->getServerState())
{
return;
}
$this->processNewConnections();
$this->processExistingConnections();
}
public function setServerState($state)
{
$this->serverState = $state;
}
public function getServerState()
{
return $this->serverState;
}
private function processNewConnections()
{
...
}
private function processExistingConnections()
{
...
if(connected client has requested that the server should stop)
{
$this->setServerState(false);
}
...
}
}
I create function for if no get one value - in this case ok - repeat and recheck other time and other time , but the problem it´s all time when check 2 or 3 times finally put me connection down
My function :
<?php
function recursive() {
if (file_exists("pol.txt")) {
print "ok";
} else {
print "bad";
usleep(1);
recursive();
}
}
recursive();
?>
The idea it´s the function test this all time and stop when other function create the file called pol.txt , but the problem it´s the function , because all time in 2 seconds put me coonection down in all brownsers
I test actually in localhost and in server with the same results
The question it´s if no possible run this kind of function or exists other way for do this without refresh page each time , because i can´t use refresh in this case
Thank´s , regards
The problem is that you are using usleep(). That delays the execution in micro-seconds so in two seconds you will have a very deep level of recursion, causing your script to error out.
For this you should probably just use a loop and make sure it ends after an x-number of seconds or iterations.
I have a web page that contains some JavaScript and performs some Ajax calls. When trying to test it using Selenium, I randomly get "PHPUnit_Extensions_Selenium2TestCase_WebDriverException: Element is no longer attached to the DOM" message, maybe once in 5 runs.
Now I'm aware of the race issue between Ajax call and test engine, and I have taken steps to protect from it, but I still have some problem. My scenario is this: I change value of the select element 1 which triggers Ajax call that removes all option sub-elements of the select element 2 and generates new option sub-elements based on the Ajax response. Testing code:
$this->select($this->byId('select1'))->selectOptionByValue('value1');
$this->myWaitForElementToAppear('#select2>option[value="value2"]');
$this->select($this->byId('select2'))->selectOptionByValue('value2');
last line triggers the error. Here is the myWaitForElementToAppear method:
public function myWaitForElementToAppear($selector, $limit = 5) {
$start = time();
while(true) {
if($start + $limit < time()) {
break;
}
try {
$this->byCssSelector($selector);
break;
} catch(PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {}
}
}
If I'm not mistaken, myWaitForElementToAppear method should ensure that desired option has been added by jQuery before it exits and thus allow it to be used on the next line. I should add that I've made sure that time-out doesn't happen here (since my method allows for it to happen) and I'm positive that it's not the case
Edit: I should add that putting sleep(1) after myWaitForElementToAppear call solves the problem, but I don't understand why the additional second is needed. Shouldn't call to myWaitForElementToAppear be enough?
There are some explanations here:
Firstly, time() has a very low precision, only returning the number of
whole seconds that have passed, which makes the whole thing quite
vague. Secondly, PHP has to sit there looping thousands of times while
it waits, essentially doing nothing. A much better solution is to use
the one of the two script sleep functions, sleep() and usleep(), which
take the amount of time to pause execution as their only parameter.
From php.net:
The idea of sleep and usleep is that by letting the cpu run a few idle
cycles so the other programs can have some cycles run of their own.
what results in better response times and lower overall system-load.
so if you have to wait for something, go to sleep for a few seconds
instead of occupying the cpu while doing absolute nothing but
waitting.
And you can use waitUntil from PHPUnit:
/* waitElementToDisappear */
$this->waitUntil(function($testCase) {
try {
$input = $testCase->byCssSelector("#select2>option[value="value2"]");
} catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
if (PHPUnit_Extensions_Selenium2TestCase_WebDriverException::NoSuchElement == $e->getCode()) {
return true;
}
}
}, 5000);
/* waitElementToAppear */
$this->waitUntil(function($testCase) {
try {
$input = $testCase->byCssSelector("#select2>option[value="value2"]");
return true;
} catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {}
}, 5000);
Is there a way in PHP to check if a function has completed processing before allowing it to run again?
I have a function that on page loads/reloads/timer event checks if DB items should be expired based on an end date (date less than now) and if date is less than now makes a duplicate of the record with the exact same information but adds 10 days to the end date. The script then sets the original record status to inactive. This is required to keep an original copy of the item in the DB and the process continues for every record.
Sometimes the script will create multiple duplicates of the same item so it seems like the script is not setting the status to inactive quick enough and when the page is reloaded/visited etc another instance of the script is run producing another duplicate record.
So is there a way to check if a function is currently running and if so ignore the new call to only ever have a single instance running?
Many many thanks
Sounds like you need a "mutex". You can try using this, or implement one yourself by creating a shared resource, such as writing an empty file to disk and then checking for its existence, and removing it when you're done.
A better solution for your specific problem though would be to set up a cron job to periodically run your database maintenance scripts rather than relying on random user requests to your page. This will ensure it won't run too often and reduce the processing per request.
For PHP:
$Running = false;
function functionName() {
if (!$Running) {
$Running= true;
//Your logic implementation here
$Running= false;
}
}
You can use same principle for jQuery functions also and cron job too.
Use a try catch
function blah() {
try {
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
}