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)
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
First of all, in my professional opinion, your boss is crazy :)
Having said that, here's some changes you can make to address your fears:
Create an array of job_execution_slots
with the same length as your jobs
array; initialize to null
values.
Before you do $.ajax()
you check whether the job_execution_slots[i]
is "taken" (not null
).
When the slot is empty, you do job_execution_slots[i] = $.ajax({...})
and make sure it's set to async: true
; keeping the reference also allows you to "kill" a job by stopping the AJAX request.
In your AJAX completion handler you do job_execution_slots[i] = null;
This basically serializes the execution per job.
Let me know if this makes sense to you; I can supply further details upon demand :)