I saw some answers explaining how to run multiple PHP scripts synchronously from one PHP file with exec function.
For example :
<?php
exec("script1.php");
exec("script2.php");
?>
But this is not what I want. My problem is that these scripts are doing intensive SQL requests so if I do that the calling PHP script will die with timeout. Increasing the timeout is not a solution.
I don't want to execute these scripts asynchronously in order to avoid to overload the MySQL database at the same time.
So I was thinking to do it in Javascript or maybe with a cron job.
In JS I would like to execute script2.php only if script1.php is finished and so on.
With JQuery I could do something like that:
<script>
myfunction();
function myfunction()
{
promise = longfunctionfirst().then(shortfunctionsecond);
}
function longfunctionfirst()
{
d = new $.Deferred();
fetch("script1.php", {})
.then( async response => await response.json())
.then(function(data) {
//Process data
});
setTimeout('alert("first function finished");d.resolve()',3000);
return d.promise()
}
function shortfunctionsecond()
{
d = new $.Deferred();
fetch("script2.php", {})
.then( async response => await response.json())
.then(function(data) {
//Process data
});
setTimeout('alert("second function finished");d.resolve()',200);
return d.promise()
}
</script>
It could be ok if I have only 2 scripts but I have more than 10.
Do you think I can find an effective solution with JS, jQuery or with cron jobs?
My Answer:
One possible solution could be to create a queue system in JavaScript where you can add all the scripts that need to be executed sequentially. Here's an example of how you could achieve this:
javascript
var scriptQueue = [
"script1.php",
"script2.php",
"script3.php",
// Add more scripts here
];
function runScriptQueue() {
if (scriptQueue.length > 0) {
var script = scriptQueue.shift();
fetch(script, {})
.then(async response => await response.json())
.then(function(data) {
// Process data
console.log(script + " finished");
runScriptQueue();
});
}
}
runScriptQueue();
In this example, we have an array `scriptQueue` containing the paths to all the PHP scripts that need to be executed sequentially. The `runScriptQueue` function will fetch and process each script one by one, waiting for the previous script to finish before moving on to the next one.
You can add as many scripts as you need to the `scriptQueue` array, and they will be executed in the order they are added.
Alternatively, you could also consider using a task scheduling library like Agenda.js or node-cron in Node.js to run the PHP scripts as cron jobs at specific intervals. This way, you can ensure that the scripts are executed sequentially without overloading the MySQL database.
Rate this post
3 of 5 based on 1553 votesComments