Skip to content

Commit 5ec0ec3

Browse files
committed
Release 0.0.4
1 parent ce4b30d commit 5ec0ec3

2 files changed

Lines changed: 24 additions & 11 deletions

File tree

Sources/AsyncTimer/AsyncTimer.swift

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import Foundation
1414

1515
public enum AsyncTimerInfo: Sendable {
1616
/// Current AsyncTimer version.
17-
public static let version = "0.0.3"
17+
public static let version = "0.0.4"
1818
}
1919

2020
/// A simple repeating timer that runs a task at a specified interval.
@@ -81,14 +81,15 @@ public final actor AsyncTimer {
8181
public func start() {
8282
stop()
8383
task = Task(priority: priority) {
84+
// one-time timer
8485
guard repeating else {
85-
// one-time timer
8686
do {
8787
try await Self.sleep(interval)
8888
await self.handler()
89-
} catch is CancellationError {
90-
// timer was cancelled
91-
await cancelHandler?()
89+
handleTaskCompletion()
90+
} catch {
91+
// task was cancelled
92+
handleTaskCancelation()
9293
}
9394
return
9495
}
@@ -103,12 +104,11 @@ public final actor AsyncTimer {
103104
if Task.isCancelled { break }
104105
try await Self.sleep(interval)
105106
}
106-
} catch is CancellationError {
107-
// timer was cancelled
108107
} catch {
109-
// unexpected error
108+
// task was cancelled
110109
}
111-
await cancelHandler?()
110+
// while loop was break or task cancelled
111+
handleTaskCancelation()
112112
}
113113
}
114114

@@ -136,6 +136,19 @@ public final actor AsyncTimer {
136136
}
137137
}
138138

139+
private extension AsyncTimer {
140+
/// Handles the task cancelation.
141+
func handleTaskCancelation() {
142+
task = nil
143+
Task { await self.cancelHandler?() }
144+
}
145+
146+
/// Handles the task completion.
147+
func handleTaskCompletion() {
148+
task = nil
149+
}
150+
}
151+
139152
public extension AsyncTimer {
140153
/// Sleep for the specified interval.
141154
static func sleep(_ interval: TimeInterval) async throws {

Tests/AsyncTimerTests/AsyncTimerTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ import Testing
171171
handler: {
172172
@MainActor in
173173
// Simulate some work
174-
for _ in 0..<1000000 {
174+
for _ in 0 ..< 1_000_000 {
175175
_ = 1 + 1
176176
}
177177
highPriorityExecutionTime = Date().timeIntervalSince1970 - startTime
@@ -186,7 +186,7 @@ import Testing
186186
handler: {
187187
@MainActor in
188188
// Simulate some work
189-
for _ in 0..<1000000 {
189+
for _ in 0 ..< 1_000_000 {
190190
_ = 1 + 1
191191
}
192192
lowPriorityExecutionTime = Date().timeIntervalSince1970 - startTime

0 commit comments

Comments
 (0)