有没有JavaScript替代Cronjob的方法?
事实上,我的老板不想再使用CronJob进行每日执行,并告诉我如果我们能用JavaScript代替CronJob就好了。
我编写了一个PHP+JavaScript代码。它基本上从数据库中收集每日任务数据(要执行的.php文件,时间间隔等),并将它们放入一个对象中。
然后,
<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>
所以,我使用了这段代码。它对基本作业很有效,但会有一些需要花费10分钟以上才能完成的大型作业(比如删除和重新填充数千行的数据库表)
- 这样做是否安全?
- 应该将“async”值设置为false还是true?
- 我意识到可能会有同时执行的作业,如果我将async设置为false,则每个作业都必须等待前一个作业完成等等,因此我需要将setTimeout值设置为所有作业的最大运行时间。
- 如果我将其设置为true,会发生什么?我的担忧是,如果一个作业不能在setTimeout间隔之前完成,则其next_run将不被设置并且它将自动重新执行。所以我应该在ajax调用之前设置next_run值吗?
回到主题,我需要这样做吗?是否有更好的解决方案或库?(我尝试过谷歌搜索,但找不到有用的内容。)
谢谢。