56 lines
1.3 KiB
Swift
56 lines
1.3 KiB
Swift
//
|
|
// TimerModel.swift
|
|
// Crush
|
|
//
|
|
// Created by Leon on 2025/8/1.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
class TimerModel {
|
|
// MARK: - Properties
|
|
private var timer: DispatchSourceTimer?
|
|
private var isSuspended: Bool = false
|
|
var timerBlock: (() -> Void)?
|
|
|
|
// MARK: - Lazy Timer
|
|
private func createTimer() -> DispatchSourceTimer {
|
|
let timer = DispatchSource.makeTimerSource(queue: .global())
|
|
timer.schedule(deadline: .now(), repeating: .milliseconds(100)) // 0.1s interval
|
|
timer.setEventHandler { [weak self] in
|
|
self?.timerBlock?()
|
|
}
|
|
return timer
|
|
}
|
|
|
|
// MARK: - Public Methods
|
|
func startTimer() {
|
|
if !isSuspended, timer != nil { return }
|
|
isSuspended = false
|
|
if timer == nil {
|
|
timer = createTimer()
|
|
}
|
|
timer?.resume()
|
|
//dlog("🔥: resume once")
|
|
}
|
|
|
|
func pauseTimer() {
|
|
guard let timer = timer, !isSuspended else { return }
|
|
isSuspended = true
|
|
timer.suspend()
|
|
//dlog("🔥: suspend once")
|
|
}
|
|
|
|
// MARK: - Deinit
|
|
deinit {
|
|
dlog("📻 audio timer dealloc")
|
|
if let timer = timer {
|
|
if isSuspended {
|
|
startTimer() // Resume to allow cancellation
|
|
}
|
|
timer.cancel()
|
|
self.timer = nil
|
|
}
|
|
}
|
|
}
|