I am using php loop in order to get to know any file changes. If the file changes occur , I am trying to stop the loop. But in my condition instead of stopping ..loop continues.
Route::get('api.chat.buffer/{job_id}',function($job_id){
$award= DB::table('job_awards')->where('job_id',$job_id)->first();
$dirname = base_path().'/files/chat/';
$filename = $award->client_id.'_'.$award->user_id.'.timelog.log';
$i =1;
for($z=0;$z<=20;$z++){
$current_file_time = filemtime($dirname.$filename);
if($_GET['timestamp']<$current_file_time){
echo json_encode(array('status'=>'success','data'=>$current_file_time,'node'=>1)); die;
break;
}
sleep(1); // this should halt for 3 seconds for every loop
}
echo json_encode(array('status'=>'success','data'=>$current_file_time,'node'=>0));
die;
});
I am creating chatting script and tracking changing while file change.
Thanks
can you use sleep function inside a for loop?. Have you tried with yield. Try assigning the numbers of loops statements to break; in this case it would be break 1; http://php.net/manual/en/control-structures.break.php
Related
<?php
require('Classes\PHPExcel.php');
$phpExcel = PHPExcel_IOFactory::load('123.xlsx');
$writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007");
$sheet = $phpExcel ->getActiveSheet();
$x=1;
while ($x<=5){
if($sheet->getCell('A'.$x)->getValue()=="1"){
$sheet->SetCellValue('B'.$x, 'Something');
}
}
$writer->save('1234.xlsx');
?>
If I remove "while" and "if" lines... code is working perfectly and its getting completed in 1 second.
but this way, it can not complete process in 60 seconds and time over occurs.
123.xlsx has just A column and 5 numbers from 1 to 5. it is just for test but again its taking so long.
I still couldn't understand where im making mistake.
in normal 123.xlsx file will be around 800 rows and 20 columns, so it will take years :)
please help
Where are you incrementing the $i?
You might need to increment $i, based on your code requirement, you might increase $i in either while loop or inside if :
$x=1;
while ($x<=5){
if($sheet->getCell('A'.$x)->getValue()=="1")
{
$sheet->SetCellValue('B'.$x, 'Something');
$x++;//Increment here?
}
$x++;//orIncrement here?
}
I'm trying to learn long poll and I'm using following PHP script:
<?php
$lastMod = filemtime('test.txt');
$counter = 10;
while ($counter > 0) {
if (filemtime('test.txt') !== $lastMod) {
echo file_get_contents('./test.txt');
exit;
}
$counter--;
sleep(1);
}
echo $lastMod;
But no matter what I do or try, it doesn't do anything when I change test.txt content during script execution.
I would be really happy if somebody told me where is the mistake.
The filemtime result is cached during runtime, so you need to reset it explicitly using clearstatcache().
Run it right before your if.
From the docs:
Note: The results of this function are cached. See clearstatcache()
for more details.
I have a problem with a counter. I need to count two variables, separated with a |, but sometimes the counter doesn't increase a variable's value.
numeri.txt (the counter):
5240|593389
This is the PHP script:
$filename="numeri.txt";
$fp=fopen($filename,"r");
if(!flock($fp,LOCK_SH))
{
while(true)
{
usleep(100000);
if(flock($fp,LOCK_SH))
{
break;
}
}
}
$contents=fread($fp,filesize($filename));
flock($fp,LOCK_UN);
fclose($fp);
$fp=fopen($filename,'a');
if(!flock($fp,LOCK_EX))
{
while(true)
{
usleep(100000);
if(flock($fp,LOCK_EX))
{
break;
}
}
}
ftruncate($fp,0);
$contents=explode("|",$contents);
$clicks=$contents[0];
$impressions=$contents[1]+1;
fwrite($fp,$clicks."|".$impressions);
flock($fp,LOCK_UN);
fclose($fp);
I set the counter to the right value but after 3-4 days the counter hasn't counted about 50 impressions (the number after "|")
How to fix the code?
Two problems:
1) There is still the opportunity to do a read, another process to write the file, then this process write the file. Millisecond timing required, but it's possible.
2) You don't actually verify the "open" works - it can fail.
The solution is to firstly check for open failure and retry, and secondly do one lock - exclusive. Paraphrased code:
while (!$fh = fopen($file, 'c+')) { // Read write, do not truncate, place pointer at start.
usleep(100000);
}
while (!flock(LOCK_EX)) {
usleep(100000);
}
$content = fread();
// Process content...
ftruncate();
fseek(0); // Or frewind();
fwrite();
fclose(); // Also releases the lock.
I have a .php script that I use for creating the list of my products.
I am on shared hosting, so I can't do a lot of queries otherwise I get a blank page.
This is how I use my script now:
script.php?start=0&end=500&indexOfFile=0 ->> make a product0.txt file with first 500 products
script.php?start=501&end=1000&indexOfFile=1 ->> product1.txt file with another 500 products
script.php?start=1001&end=1500&indexOfFile=2 ->> product2.txt file with last 500 products
How can I modify the script so it will make all these files automatically, so that I don't have to change each time the link manually?
I would like to click a button which will do this:
make the product0.txt file with the first 500 products
wait 5 seconds
make the product1.txt file with with another 500 products
wait 5 seconds
make the product2.txt file with the last 500 products
use:
sleep(NUMBER_OF_SECONDS);
before starting your actions, use
sleep(5);
or:
usleep(NUMBER_OF_MICRO_SECONDS);
In Jan2018 the only solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
i use this
$i = 1;
$last_time = $_SERVER['REQUEST_TIME'];
while($i > 0){
$total = $_SERVER['REQUEST_TIME'] - $last_time;
if($total >= 2){
// Code Here
$i = -1;
}
}
you can use
function WaitForSec($sec){
$i = 1;
$last_time = $_SERVER['REQUEST_TIME'];
while($i > 0){
$total = $_SERVER['REQUEST_TIME'] - $last_time;
if($total >= 2){
return 1;
$i = -1;
}
}
}
and run code =>
WaitForSec(your_sec);
Example :
WaitForSec(5);
OR
you can use sleep
Example :
sleep(5);
I am on shared hosting, so I can't do a lot of queries otherwise I get a blank page.
That sounds very peculiar. I've got the cheapest PHP hosting package I could find for my last project - and it does not behave like this. I would not pay for a service which did. Indeed, I'm stumped to even know how I could configure a server to replicate this behaviour.
Regardless of why it behaves this way, adding a sleep in the middle of the script cannot resolve the problem.
Since, presumably, you control your product catalog, new products should be relatively infrequent (or are you trying to get stock reports?). If you control when you change the data, why run the scripts automatically? Or do you mean that you already have these URLs and you get the expected files when you run them one at a time?
In https://www.php.net/manual/es/function.usleep.php
<?php
// Wait 2 seconds
usleep(2000000);
// if you need 5 seconds
usleep(5000000);
?>
So i've been trying to write this little piece of code to read a file (status.txt), search it for 1 of 4 keywords and loop until either time runs out (5 minutes) or it finds one of the words. I've already written a few simple php scripts to write the words to a txt file, but I can't seem to get this part to work. It either doesn't clear the file in the beginning or seems to hang and never picks up the changes. Any advice would be hugely helpful.
<?php
//Variables
$stringG = "green";
$stringR = "red";
$stringB = "blue";
$stringO = "orange";
$clear = "";
$statusFile = "status.txt";
//erase file
$fh = fopen($statusFile, 'w'); //clear the file with "clear"
fwrite($fh, $clear);
fclose($fh);
//Insert LOOP
$counter = 0;
while ( $counter <= 10 ) {
//echo "loop begun";
// Read THE FILE
$fh = fopen($statusFile, 'r');
$data = fread($fh, filesize($statusFile));
fclose($fh);
//process the file
if(stristr($data,$stringG)) {
echo "Green!";
$counter = $counter + 30; //stop if triggered
}
elseif (stristr($data,$stringR)) {
echo "Red";
$counter = $counter + 30; //stop if triggered
}
elseif (stristr($data,$stringB)) {
echo "Blue";
$counter = $counter + 30; //stop if triggered
}
elseif (stristr($data,$stringO)) {
echo "Orange";
$counter = $counter + 30; //stop if triggered
}
else {
//increment loop counter
$counter = $counter + 1;
//Insert pause
sleep(10);
}
}
?>
You should open the file before your read loop, and close it after the loop. As in :
open the file
loop through the lines in the file
close the file
Also, if you clear the file before you read it, isn't it going to be empty every time?
Well, first of all, you don't need to "clear" the file this way... The "w" option in fopen will already do that for you.
Also, I wouldn't try to read the whole file at once, because, if it's very large, that won't work without intense memory usage.
What you should do is read the file sequentially, which means you always read a fixed amount of bytes and look for the keywords. To avoid losing keywords which are cut in half by your reading mechanism, you could make your reads overlay a bit (the length of your longest keyword-1), to solve that problem.
Then you should modify your while loop so that it also checks if you are at the end of the file ( while(!feof($fh)) ).
PS: It has been mentioned that you clear your file before reading it. What I understood is that your file gets a lot of input really fast, so you expect it to already have content again when you reopen it. If that's not the case, you really need to rethink your logic ;)
PPS: You don't need to abort your while loop by incrementing your counter variable past the boundaries you define. You can also use the break-keyword.
You haven't included the code which deletes the file in the while loop, so it only clears the file once. Also, I'd use unlink($statusFile); to delete the file.
You should rather use for cycle. And to your problem - you clear the file, then get the data from it. Try dumping this $data, you'll end up with string(0) "" for sure. First, save the data, then clear the file.
Edit: If you are changing the file in the loop itself in another thread, there's another problem. You should look after anatomic file stream. For example, you can use Nette SafeStream class.