@@ -14,7 +14,7 @@ import Foundation
1414
1515public 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+
139152public extension AsyncTimer {
140153 /// Sleep for the specified interval.
141154 static func sleep( _ interval: TimeInterval ) async throws {
0 commit comments