TaskScheduler.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. //
  2. // TaskScheduler.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2025-01-10.
  6. // Copyright © 2025 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. enum TaskID: CaseIterable {
  11. case profile
  12. case deviceStatus
  13. case treatments
  14. case fetchBG
  15. case minAgoUpdate
  16. case calendarWrite
  17. case alarmCheck
  18. }
  19. struct ScheduledTask {
  20. var nextRun: Date
  21. var action: () -> Void
  22. }
  23. class TaskScheduler {
  24. static let shared = TaskScheduler()
  25. // Thread-safety: a serial queue so we don’t manipulate tasks from multiple threads at once
  26. private let queue = DispatchQueue(label: "com.LoopFollow.TaskSchedulerQueue")
  27. private var tasks: [TaskID: ScheduledTask] = [:]
  28. private var currentTimer: Timer?
  29. private init() {}
  30. // MARK: - Public API
  31. func scheduleTask(id: TaskID, nextRun: Date, action: @escaping () -> Void) {
  32. queue.async {
  33. let timeString = self.formatTime(nextRun)
  34. LogManager.shared.log(category: .taskScheduler, message: "scheduleTask(\(id)): next run = \(timeString)", isDebug: true)
  35. self.tasks[id] = ScheduledTask(nextRun: nextRun, action: action)
  36. self.rescheduleTimer()
  37. }
  38. }
  39. func rescheduleTask(id: TaskID, to newRunDate: Date) {
  40. let timeString = self.formatTime(newRunDate)
  41. LogManager.shared.log(category: .taskScheduler, message: "Reschedule Task \(id): next run = \(timeString)", isDebug: true)
  42. queue.async {
  43. guard var existingTask = self.tasks[id] else {
  44. return
  45. }
  46. existingTask.nextRun = newRunDate
  47. self.tasks[id] = existingTask
  48. self.checkTasksNow()
  49. }
  50. }
  51. func checkTasksNow() {
  52. queue.async {
  53. self.fireOverdueTasks()
  54. self.rescheduleTimer()
  55. }
  56. }
  57. // MARK: - Private
  58. /// Updated signature to include info about who called us, and which task triggered it (if any).
  59. private func rescheduleTimer() {
  60. // Invalidate any existing timer
  61. currentTimer?.invalidate()
  62. currentTimer = nil
  63. guard let (_, earliestTask) = tasks.min(by: { $0.value.nextRun < $1.value.nextRun }) else {
  64. LogManager.shared.log(category: .taskScheduler, message: "No tasks, no timer scheduled.")
  65. return
  66. }
  67. let interval = earliestTask.nextRun.timeIntervalSinceNow
  68. let safeInterval = max(interval, 0)
  69. // Comment out this block to simulate heartbeat execution only
  70. DispatchQueue.main.async {
  71. self.currentTimer = Timer.scheduledTimer(withTimeInterval: safeInterval, repeats: false) { [weak self] _ in
  72. guard let self = self else { return }
  73. self.queue.async {
  74. self.fireOverdueTasks()
  75. self.rescheduleTimer()
  76. }
  77. }
  78. }
  79. }
  80. private func fireOverdueTasks() {
  81. BackgroundAlertManager.shared.scheduleBackgroundAlert()
  82. let now = Date()
  83. let tasksToSkipAlarmCheck: Set<TaskID> = [.deviceStatus, .treatments, .fetchBG]
  84. for taskID in TaskID.allCases {
  85. guard let task = tasks[taskID], task.nextRun <= now else {
  86. continue
  87. }
  88. // Check if we should re-schedule alarmCheck till after other tasks are done
  89. if taskID == .alarmCheck {
  90. let shouldSkip = tasksToSkipAlarmCheck.contains {
  91. guard let checkTask = tasks[$0] else { return false }
  92. return checkTask.nextRun <= now || checkTask.nextRun == .distantFuture
  93. }
  94. if shouldSkip {
  95. //LogManager.shared.log(category: .taskScheduler, message: "Skipping alarmCheck because one of the specified tasks is due or set to distant future.", isDebug: true)
  96. guard var existingTask = self.tasks[taskID] else {
  97. continue
  98. }
  99. existingTask.nextRun = Date().addingTimeInterval(5)
  100. self.tasks[taskID] = existingTask
  101. continue
  102. }
  103. }
  104. var updatedTask = task
  105. updatedTask.nextRun = .distantFuture
  106. tasks[taskID] = updatedTask
  107. LogManager.shared.log(category: .taskScheduler, message: "Executing task \(taskID)", isDebug: true)
  108. DispatchQueue.main.async {
  109. task.action()
  110. }
  111. }
  112. }
  113. private func formatTime(_ date: Date) -> String {
  114. let formatter = DateFormatter()
  115. formatter.dateStyle = .none
  116. formatter.timeStyle = .medium
  117. return formatter.string(from: date)
  118. }
  119. }