//配置项
var config={
    time:"01:00:00",//每天几点执行
    interval:1,//隔几天执行一次
    runNow:true//是否立即执行
};
timerTask(config);

//定时任务逻辑
function timerTask(config){
    if(config.runNow){
        //如果配置了立刻运行则立刻运行任务函数
        cleanLog();
    }

     //获取下次要执行的时间,如果执行时间已经过了今天,就让把执行时间设到明天的按时执行的时间
     var nowTime=new Date().getTime();
     var timePoint=config.time.split(":").map(i=>parseInt(i));
     
     var recent =new Date().setHours(...timePoint);//获取执行时间的时间戳
     
     if(recent <= nowTime){
         recent+=24*60*60*1000;
     }
     
     //未来程序执行的时间减去现在的时间,就是程序要多少秒之后执行
     var doRunTime=recent-nowTime;
     setTimeout(function(){
         cleanLog();
         //没隔多少天在执执行
         var intTime=config.interval*24*60*60*1000;
         setInterval(function(){
             cleanLog();

         },intTime);

     },doRunTime);

}

//清空日志逻辑
function cleanLog(){
    //清空web运行程序的日志
    console.log("程序执行了!");

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐