A Repeating timer in Swift 6

I'm using that repeating timer for processing information repeatedly:

actor RepeatingTimer {
    private var task: Task<Void, Never>?
    private var isPaused = false
   
    func start(duration: Double, onTick: @escaping () -> Void) {
        task?.cancel() // Cancel any existing timer
        isPaused = false
        task = Task {
            while !Task.isCancelled {
                // Check if paused
                if !isPaused {
                    onTick()
                }
                // Sleep for the interval
                try? await Task.sleep(for: .seconds(duration))
            }
        }
    }

    func pause() {
        isPaused = true
    }

    func resume() {
        isPaused = false
    }

    func stop() {
        task?.cancel()
        task = nil
    }
}`

Yet when I call it from another actor with:

await timer.start(duration: interval, onTick:{
                self.process()
            })

I get:

Sending 'self'-isolated value of non-Sendable type '() -> ()' to actor-isolated instance method 'start(duration:onTick:)' risks causing races in between 'self'-isolated and actor-isolated uses

Is there some more stable option for managing repeating timers, or how to solve this error?

Answered by fbartolom in 886753022

I fixed it by inserting @Sendable in the closure and changing the calling function to:

await timer.start(duration: interval, onTick:{
                Task.init{
                    await self.process()
                }
            })
Accepted Answer

I fixed it by inserting @Sendable in the closure and changing the calling function to:

await timer.start(duration: interval, onTick:{
                Task.init{
                    await self.process()
                }
            })
A Repeating timer in Swift 6
 
 
Q