CronJob的Javascript替代品

Javascript alternative to CronJob

本文关键字:替代品 Javascript CronJob      更新时间:2023-09-26

有没有Cronjob的javascript替代品?

问题是,我的老板不想再使用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+ 分钟才能完成(例如删除并重新填充具有数千行的数据库表)

  • 安全吗?
  • 我应该将"异步"值设置为 false 还是不?
  • 我知道可能存在必须
  • 同时执行的作业的情况,如果我设置异步 false,则每个作业都需要等待才能完成上一个作业等,因此我需要将 setTimeout 值设置为所有作业的总最大运行时间。
  • 如果我把它设置为真,会发生什么?我担心的是,如果作业无法在设置超时间隔之前完成,则next_run不会设置,它会自动重新执行。那么我应该在 ajax 调用之前设置next_run值吗?

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

谢谢

首先,在我的专业意见中,你的老板疯了:)

话虽如此,您可以进行以下一些更改来解决您的恐惧:

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

  2. 在执行$.ajax()之前,请检查job_execution_slots[i]是否被"占用"(而不是null)。

  3. 当插槽为空时,你执行job_execution_slots[i] = $.ajax({...})并确保它设置为async: true;保留引用还允许您通过停止AJAX请求来"终止"作业。

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

这基本上序列化了每个作业的执行。

让我知道这对你来说是否有意义;我可以根据需要提供更多详细信息:)