forked from exelban/stats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRepeater.swift
72 lines (58 loc) · 1.62 KB
/
Repeater.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// Repeater.swift
// Kit
//
// Created by Serhiy Mytrovtsiy on 27/06/2022.
// Using Swift 5.0.
// Running on macOS 10.15.
//
// Copyright © 2022 Serhiy Mytrovtsiy. All rights reserved.
//
import Foundation
public enum State {
case paused
case running
}
public class Repeater {
private var callback: (() -> Void)
private var state: State = .paused
private var timer: DispatchSourceTimer = DispatchSource.makeTimerSource(queue: DispatchQueue(label: "eu.exelban.Stats.Repeater", qos: .default))
public init(seconds: Int, callback: @escaping (() -> Void)) {
self.callback = callback
self.setupTimer(seconds)
}
deinit {
self.timer.cancel()
self.start()
}
private func setupTimer(_ interval: Int) {
self.timer.schedule(
deadline: DispatchTime.now() + Double(interval),
repeating: .seconds(interval),
leeway: .seconds(0)
)
self.timer.setEventHandler { [weak self] in
self?.callback()
}
}
public func start() {
guard self.state == .paused else { return }
self.timer.resume()
self.state = .running
}
public func pause() {
guard self.state == .running else { return }
self.timer.suspend()
self.state = .paused
}
public func reset(seconds: Int, restart: Bool = false) {
if self.state == .running {
self.pause()
}
self.setupTimer(seconds)
if restart {
self.callback()
self.start()
}
}
}