fix: timermanager async tasks and exception catching

This commit is contained in:
Ben Allfree 2023-01-24 16:20:30 +00:00
parent e27457b4df
commit 486285b56e

View File

@ -4,6 +4,8 @@ import { logger } from './Logger'
export type UnixTimestampMs = number export type UnixTimestampMs = number
export type TimerCanceler = () => void export type TimerCanceler = () => void
export type RepeatableTimerCallback = () => boolean | Promise<boolean>
export type TimerCallback = () => void | Promise<void>
export type TimeManagerConfig = {} export type TimeManagerConfig = {}
export type TimeManager = ReturnType<typeof createTimerManager> export type TimeManager = ReturnType<typeof createTimerManager>
@ -14,12 +16,16 @@ export const createTimerManager = (config: TimeManagerConfig) => {
const cleanups: any = {} const cleanups: any = {}
let isShutDown = false let isShutDown = false
const add = (cb: () => void, ms: UnixTimestampMs) => { const add = (cb: TimerCallback, ms: UnixTimestampMs) => {
if (isShutDown) throw new Error(`Already shut down`) if (isShutDown) throw new Error(`Already shut down`)
const idx = i++ const idx = i++
const tid = setTimeout(() => { const tid = setTimeout(async () => {
cancel() cancel()
cb() try {
await cb()
} catch (e) {
error(e)
}
}, ms) }, ms)
const cancel = () => { const cancel = () => {
clearTimeout(tid) clearTimeout(tid)
@ -37,10 +43,7 @@ export const createTimerManager = (config: TimeManagerConfig) => {
dbg(`done`, cleanups) dbg(`done`, cleanups)
} }
const repeat = ( const repeat = (cb: RepeatableTimerCallback, ms: UnixTimestampMs) => {
cb: () => Promise<boolean> | boolean,
ms: UnixTimestampMs
) => {
let _unsub: TimerCanceler | undefined = undefined let _unsub: TimerCanceler | undefined = undefined
const _again = async () => { const _again = async () => {
const shouldRepeat = await cb() const shouldRepeat = await cb()