Javascript替代CronJob

时间:2012-06-09 08:55:53

标签: php javascript jquery cron

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多分钟才能完成(比如删除和重新填充数千行的数据库表)

  • 安全吗?
  • 我应该设置&#34; async&#34;值是否为假?
  • 我意识到可能存在必须同时执行的作业的情况,如果我设置async false,则每个作业都需要等待完成上一个作业等等所以我需要设置setTimeout值到所有作业的总最大运行时间。
  • 如果我确定它可能发生什么?我担心的是,如果一个工作不能在setTimeout间隔之前完成,它的next_run将不会被设置,它将自动重新执行。那么我应该在ajax调用之前设置next_run值吗?

回到主题,我应该做所有这些吗?有更好的解决方案或库吗? (我用谷歌搜索,但找不到任何有用的东西。)

谢谢

1 个答案:

答案 0 :(得分:1)

首先,在我的专业观点中,你的老板很疯狂:)

话虽如此,您可以通过以下方式解决恐惧问题:

  1. 创建一个job_execution_slots数组,其长度与jobs数组相同;初始化为null值。

  2. 在您$.ajax()之前,检查job_execution_slots[i]是否已被“取走”(不是null)。

  3. 当广告位为空时,您执行job_execution_slots[i] = $.ajax({...})并确保将其设置为async: true;保持引用还允许您通过停止AJAX请求来“杀死”作业。

  4. 在您的AJAX完成处理程序中,执行job_execution_slots[i] = null;

  5. 这基本上将每个作业的执行序列化。

    如果这对你有意义,请告诉我。我可以根据需要提供更多细节:)