最近在项目中有这样一个定时任务的需求,觉得能应用的地方还是挺多的,在这里分享一下
data(){
return{
// 定时任务配置
config: {
time: '08:00:00', // 每天几点执行
interval: 1, // 隔几天执行一次
runNow: false, // 是否立即执行
intervalTimer: '',
timeOutTimer: ''
}
}
}
// 一定要记得在组件销毁阶段清除定时器
beforeDestroy () {
// 清除任务定时器
clearInterval(this.config.intervalTimer)
// 清除定时器timeout
clearTimeout(this.config.timeOutTimer)
},
methods:{
// 设置定时任务
setTimedTask() {
// 默认为false,true为立即触发,看你的需求,如果设置为true则立刻运行任务函数
if (this.config.runNow) {
this.initBusinessFn()
}
// 获取下次要执行的时间,如果执行时间已经过了今天,就让把执行时间设到明天的按时执行的时间
const nowTime = new Date().getTime()
const timePoint = this.config.time.split(':').map((i) => parseInt(i))
let recent = new Date().setHours(...timePoint) // 获取执行时间的时间戳
if (recent <= nowTime) {
recent += 24 * 60 * 60 * 1000
}
// 要执行的时间减去现在的时间,就是程序要多少秒之后执行
const doRunTime = recent - nowTime
this.config.timeOutTimer = setTimeout(this.setTimer, doRunTime)
},
// 设置定时器
setTimer () {
console.log('进入定时器了')
// 这里是将在你设置的时间点执行你的业务函数
this.initTopTenBusiness()
// 每隔多少天再执行一次,这里设置的是24小时
const intTime = this.config.interval * 24 * 60 * 60 * 1000
this.config.intervalTimer = setInterval(this.initBusinessFn, intTime)
},
// 你的业务函数 这里列举的是刷新浏览器
initBusinessFn() {
console.log('定时任务函数触发了,即将刷新页面')
window.location.reload()
}
}