LeaseWatcher.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const Logger = require('../Logger')
  2. const { TaskScheduler } = require('./TaskScheduler')
  3. class LeaseWatcher {
  4. constructor(options = {}) {
  5. this.intervalMs = options.intervalMs || 30 * 1000
  6. this.logger = options.logger || new Logger()
  7. this.scheduler = options.scheduler || new TaskScheduler()
  8. this.timer = null
  9. this.running = false
  10. }
  11. async tick() {
  12. if (this.running) {
  13. this.logger.warn('[QK][LeaseWatcher] 上一轮巡检尚未结束,跳过本次执行')
  14. return
  15. }
  16. this.running = true
  17. try {
  18. const count = await this.scheduler.requeueExpiredTasks()
  19. if (count > 0) {
  20. this.logger.info(`[QK][LeaseWatcher] 已将 ${count} 个失联任务重新入队`)
  21. }
  22. } catch (err) {
  23. this.logger.error(`[QK][LeaseWatcher] 执行失败:${err.stack || err}`)
  24. } finally {
  25. this.running = false
  26. }
  27. }
  28. start() {
  29. if (this.timer) {
  30. return this.timer
  31. }
  32. this.logger.info(`[QK][LeaseWatcher] 已启动,巡检间隔 ${this.intervalMs}ms`)
  33. this.tick()
  34. this.timer = setInterval(() => this.tick(), this.intervalMs)
  35. return this.timer
  36. }
  37. stop() {
  38. if (this.timer) {
  39. clearInterval(this.timer)
  40. this.timer = null
  41. this.logger.info('[QK][LeaseWatcher] 已停止')
  42. }
  43. }
  44. }
  45. module.exports = LeaseWatcher