Reputation: 6668
How to execute function in loop ONLY when is previous execution done?
I use one API where I need to send email to 2000 users per each session automaticly. I use corn job for that but I need to create some kind of pagination in database becouse I currently have arround 50.000 users. I know how to create pagination and send in loop but problem is server time. Execution of script is arround 5 min what return me error 500. Provider not allow me to expand execution time.
I need in PHP to Send first 2000 emails, after execution to start new execution etc. I try with ajax and work perfect but cronjob not execute HTML.
What to do?
Here is AJAX solution:
(function($){
var setup = {
page : 0,
total : 30
},
sendAjax = function(page){
if(page > setup.total)
{
return false;
}
else
{
$.ajax({
url: "/ajax/daily-request.php",
type:"POST",
data: "page="+page+"&total="+setup.total
}).fail(function(jqXHR, textStatus){
console.log("AJAX Request failed: " + textStatus);
}).done(function(num){
num = $.trim(num);
setTimeout(function(){
sendAjax(num);
console.log("User Group "+num+" Request Send!");
////////// DEBUG //////////
// sendAjax(setup.page);
// console.log(setup.page);
// setup.page++;
},1);
});
}
}
$(document).ready(function(){
sendAjax(setup.page);
});
}(jQuery));
Upvotes: 2
Views: 180
Reputation: 29
I read your problem very carefully .All you need to do is just use 'sleep()' function in php which will make your server sleep for given min so that you server will not give 500 error.
Upvotes: 1
Reputation: 623
in your PHP
<?php
$page = isset($_GET["page"]) $_GET["page"] : 0 ;//get page or handle first 1st page
using $page you can use your pagination to handle pages 0-infinate
.... your email loop for first 1000 emails
.... check that there is more
if($page != $lastpage){
header("location: daily-request.php?page=".($page+1));
}
//end of the file
?>
this will force the file to reload with a new page until it has none left setting it to 1000 ensures that you will not be sending to many on page allowing the server time to switch the pages without timeout's.
for the sql bit all u need to do is
$start = $page*1000;
SELECT * FROM `table` LIMIT $start, 1000;
this way you do not have to edit cron job just let it run and the file will take over after the first ini of it, then it will stop when pages run out and stop the loop;
Upvotes: 2