Invalidating a Timer created multiple times

207 Views Asked by At

I am trying to invalidate a Timer which is created multiple times in a class. Firstly I create a global Timer;

var musicTimer: Timer?

And I initiate it.

self.musicTimer = Timer.scheduledTimer(
    timeInterval: 2.0,
    target: self,
    selector: #selector(startMusicOnCorrectTime),
    userInfo: nil,
    repeats: true)

Then somehow I need to invalidate the timer because I need to stop calling a function.

self.musicTimer?.invalidate()

And then I need to recreate this timer with the same parameters.

self.musicTimer = Timer.scheduledTimer(
    timeInterval: 2.0,
    target: self,
    selector: #selector(startMusicOnCorrectTime),
    userInfo: nil,
    repeats: true)

But this time when I need to invalidate it, I cannot. During the class lifecycle, I need this sequence multiple times and the amount is not exact.

1

There are 1 best solutions below

0
dr_barto On

Hard to say without a full code example, but here's an idea. In case you are calling invalidate from a different thread than you started it on (e.g. you start it on the main thread but invalidate it on a background thread), it won't work according to the docs:

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.