21 lines
953 B
TypeScript
21 lines
953 B
TypeScript
type WorkerState = { timer: ReturnType<typeof setInterval>; active: number; stopped: boolean }
|
|
const globalWorker = globalThis as typeof globalThis & { __detailGeneratorWorker?: WorkerState }
|
|
|
|
export function ensureDetailGeneratorWorkerStarted(): void {
|
|
if (process.env.DETAIL_GENERATOR_ENABLED !== 'true' || globalWorker.__detailGeneratorWorker) return
|
|
const tick = () => {
|
|
const state = globalWorker.__detailGeneratorWorker
|
|
if (!state || state.stopped) return
|
|
while (state.active < 2) {
|
|
state.active += 1
|
|
void import('./jobs').then(({ runDetailGeneratorWorkerOnce }) => runDetailGeneratorWorkerOnce())
|
|
.catch(() => { console.error('[detail-generator] 队列检查失败,请检查数据库迁移与连接') })
|
|
.finally(() => { state.active -= 1 })
|
|
}
|
|
}
|
|
const timer = setInterval(tick, 2_000)
|
|
timer.unref?.()
|
|
globalWorker.__detailGeneratorWorker = { timer, active: 0, stopped: false }
|
|
tick()
|
|
}
|