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多分钟才能完成(比如删除和重新填充数千行的数据库表)
回到主题,我应该做所有这些吗?有更好的解决方案或库吗? (我用谷歌搜索,但找不到任何有用的东西。)
谢谢
答案 0 :(得分:1)
首先,在我的专业观点中,你的老板很疯狂:)
话虽如此,您可以通过以下方式解决恐惧问题:
创建一个job_execution_slots
数组,其长度与jobs
数组相同;初始化为null
值。
在您$.ajax()
之前,检查job_execution_slots[i]
是否已被“取走”(不是null
)。
当广告位为空时,您执行job_execution_slots[i] = $.ajax({...})
并确保将其设置为async: true
;保持引用还允许您通过停止AJAX请求来“杀死”作业。
在您的AJAX完成处理程序中,执行job_execution_slots[i] = null;
这基本上将每个作业的执行序列化。
如果这对你有意义,请告诉我。我可以根据需要提供更多细节:)