calling an async function from within a timer

4.8k Views Asked by At

I have an async function that has to be called every given time from within a timer. In order to avoid an Xcode error,

func firetimer()  {
      
         let newtimer = Timer(timeInterval: 1.0, repeats: true) { newtimer in
            self.myAsyncFunction() // 'async' call in a function that does not support concurrency
        }
        RunLoop.current.add(newtimer, forMode: .common)
    }

I tried to put it into a task but this gives a "Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)" error while running.

func firetimer()  {
      
         let newtimer = Timer(timeInterval: 1.0, repeats: true) { newtimer in
             Task{
            await self.myAsyncFunction() // not working
             }
        }
        RunLoop.current.add(newtimer, forMode: .common)
    }

In fact I don't need any waiting, the next occurence of the function can be called when the latter is still working. Any hint on what to do? thanks!

1

There are 1 best solutions below

3
On

Try creating a supporting function:

  1. The supporting function is synchronous but calls myAsyncFunction asynchronously:
func mySyncFunction() {

    // Call the asynchronous function
    Task {
        await self.myAsyncFunction()
    }
}
  1. Call the supporting function from fireTimer
func fireTimer()  {
      
         let newTimer = Timer(timeInterval: 1.0, repeats: true) { newTimer in
            self.mySyncFunction()    // Synchronous
        }
        RunLoop.current.add(newTimer, forMode: .common)
    }
}