pprochazka72
pprochazka72

Reputation: 562

Scheduled Timer won't fire

I am trying out Swift as a language for CLI tool, which is supposed to serve as a simple web crawler.

In my main file I create an instance of APIFetcher class. In the initialiser of APIFetcher I instantiate an instance of Timer with the given time interval. Once I call startQuerying method, it adds Timer to the main run loop - at this point I would expect performTask method would be invoked, but it isn't. What am I doing wrong?

    @available(OSX 10.12, *)
    public init(with interval: TimeInterval) {
        self.timer = Timer(timeInterval: interval, repeats: true) { _ in
            self.performTask()
        }
    }

    deinit {
        self.timer?.invalidate()
        self.timer = nil
    }

    public func startQuerying(_ url: URL) {
        guard let unwrappedTimer = self.timer else { return }

        RunLoop.main.add(unwrappedTimer, forMode: .defaultRunLoopMode)
    }

    func performTask() {
        print("Performed scheduled task")
    }

Upvotes: 2

Views: 490

Answers (1)

pprochazka72
pprochazka72

Reputation: 562

Thanks vadian you are right, I added the timer to run loop, but never actually started it. This fixes the whole issue:

RunLoop.main.add(unwrappedTimer, forMode: .defaultRunLoopMode)
RunLoop.main.run()

Also, see When Would You Use a Run Loop? documentation

Upvotes: 3

Related Questions