某公司需求 定时任务,0,8,16点上下班时间段,请求后操作一些逻辑。 刚开始想的定时器,加上dayjs 用起来就是香
// 引入 dayjs
import dayjs from 'dayjs'
// ...
data: {
timerObj: {},
// 每天的这个时间段 执行,执行过第二天还要执行。依次类推
watchTimeArr: [
{
key: "8-10",
timeVal: dayjs().hour(8).minute(-10).second(0).millisecond(0),
},
{ key: "8+10",
timeVal: dayjs().hour(8).minute(10).second(0).millisecond(0)
}
...
]
},
methods: {
loopTime({ key, timeVal, delayTime }, execFn) {
// 设置定时器,等待指定的毫秒数后执行请求
this.timerObj[key] = setTimeout(() => {
// 执行请求任务
if(delayTime >= 0) {
execFn && execFn();
}
// 获取明天的现在的时间, 轮询执行明天同时间的任务
const tomorrowNow = dayjs(timeVal).add(1, "day");
// 计算间隔的毫秒数
const oneDayTimestamp = tomorrowNow.diff(timeVal);
this.loopTime({ key, timeVal: tomorrowNow, delayTime: oneDayTimestamp }, execFn);
}, delayTime);
}
},
mounted() {
const now = dayjs();
this.watchTimeArr.forEach(timeItem => {
let delayTime = timeItem.timeVal.diff(now);
this.loopTime({ ...timeItem, delayTime }, this.getDutyInfo)
})
},
beforeMount() {
// 清除绑定的定时器
Object.keys(this.timerObj).forEach(timeKey => {
clearTimeout(this.timerObj[timeKey])
})
}