设定配置data
data() {config: {time: '00:00:00', // 每天几点执行interval: 1, // 隔几天执行一次runNow: true, // 是否立即执行intervalTimer: '',timeOutTimer: ''}}
getBussTop10DataByTimer() {if (this.config.runNow) {// 如果配置了立刻运行则立刻运行任务函数this.initTopTenBusiness()}// 获取下次要执行的时间,如果执行时间已经过了今天,就让把执行时间设到明天的按时执行的时间var nowTime = new Date().getTime()var timePoint = this.config.time.split(':').map((i) => parseInt(i))var recent = new Date().setHours(...timePoint) // 获取执行时间的时间戳if (recent <= nowTime) {recent += 24 * 60 * 60 * 1000}// 未来程序执行的时间减去现在的时间,就是程序要多少秒之后执行var doRunTime = recent - nowTimethis.config.timeOutTimer = setTimeout(this.setTimer, doRunTime)},setTimer() {console.log('进入定时器')//配置后的第一天12点执行this.initTopTenBusiness()// 每隔多少天再执行一次var intTime = this.config.interval * 24 * 60 * 60 * 1000this.config.intervalTimer = setInterval(this.initTopTenBusiness, intTime)}
清除定时器
beforeDestroy() {console.log('关闭任务定时器',this.config.intervalTimer)clearInterval(this.config.intervalTimer)console.log('清除定时器timeout', this.config.timeOutTimer)clearTimeout(this.config.timeOutTimer)}
如果觉得《VUE定时器任务(每天定时12点执行)》对你有帮助,请点赞、收藏,并留下你的观点哦!