TypeScript定义数字范围类型即仅包含【小时:分钟】的时间类型,每天指定时间点执行任务
有时我们需要定义一些特定数字范围的类型,比如小时:00-23、分钟 00-59, 和时间类型: [00-23]:[00-59],
比如每天晚上默认2:30执行任务:
type zeroToNine = 0|1|2|3|4|5|6|7|8|9
type zeroToTwo = 0|1|2|''
type zeroToSix = 0|1|2|3|4|5|6|''
export type Hour = `${zeroToTwo}${zeroToNine}`
export type Minute = `${zeroToSix}${zeroToNine}`
export type Time = `${Hour}:${Minute}`
//Usage
export const startTask = (_time: Time = '02:30') => {
let [ hour, minute ] = _time.split(':').map(tag => parseInt(tag))
const time = new Date()
time.setHours(hour)
time.setMinutes(minute)
time.setSeconds(0)
let wait = time.getTime() - Date.now()
if (wait < 0) {
//Add 1 day
wait += 24 * 3600 * 1000
}
const start = new Date(wait + Date.now())
console.log(`Task start at ${start.toLocaleString()}`)
setTimeout(() => {
setInterval(yourTaskFunction, 24 * 3600 * 1000)
}, wait)
}
回复 (0)
微信扫码 立即评论