macOS上でTimerを定期的に動かそうとすると動いてくれなくて、調べました。
iOSの情報は多いのですが、そのままでは動きませんでした。
ポイントは、TimerクラスのタイプメソッドのscheduledTimer(timeInterval:target:selector:userInfo:repeats:)を実行した後に
RunLoop.main.add(self.timer!, forMode: .common)
をしないと動きません。
多くのサイトには、forMode:で.defaultを指定していますが、これでは動かず、.commonを指定するとよいです。
簡単なサンプルコード
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
self.timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.timerUpdate), userInfo: nil, repeats: true)
RunLoop.main.add(self.timer!, forMode: .common)
}
@objc func timerUpdate() {
print("Timer Start")
//ここで実行したいことを書く
print("Timer End")
}
