Is there any javascript alternative to Cronjob?
The thing is, my boss doesn't want to use CronJob anymore for daily executions and told me that if we can do it with javascript instead of CronJob.
I wrote a php+javascript code. It basically collects the daily tasks data (which .php file to execute, what is the time interval etc.) from the database and put them in an object.
Then,
<script>
function mainFunc(){
for(var i=0; i<sizeOfJobs(); i++){ //traverse in the object
currentDate = new Date();
//if any of the jobs execution time has come, execute it
if(jobs[i]['next_run'] <= currentDate){
$.ajax({
url: jobs[i]['file_location'] ,
async: false, //this is another question, look below please
success: function(data){
//after the finish, set next_run and last_run
currentDate = new Date();
jobs[i]['last_run'] = currentDate;
var nextRun = new Date();
nextRun.setTime(currentDate.getTime() + (jobs[i]['interval'] * 60 * 1000));
jobs[i]['next_run'] = nextRun;
}
});
}
}
//repeat
//currently 10 sec but it will increase according to jobs max runtime
setTimeout(mainFunc,10000);
}
$(document).ready(function(){
setTimeout(mainFunc,10000);
})
</script>
So, I use this code. It works fine for basic jobs but there will be a huge jobs which will take 10+ min to finish (like deleting and refilling a db table with thousands of rows)
- Is it safe?
- Should I set "async" value to false or not?
- I'm aware of the situation that there could be jobs which has to execute at the same time and if I set async false, every job needs to wait to finish the previous job etc. so I need to set setTimeout value to total max runtime of all the jobs.
- If I set it true what it could be happen? My fear is, if a job can't finish before setTimeout interval, it's next_run will not be set and it will automatically re-execute. so should I set next_run value before the ajax call?
Back to the main topic, should I need to do all of this? Is there a better solution or library? (I googled but couldn't find anything useful.)
Thank you