如何在 iOS 中以固定时间间隔重复执行任务

iosapps/applicationsmobile development更新于 2026/2/15 18:07:17

Apple 预定义了 Timer 类,它会在特定时间间隔后触发,并向目标对象发送指定消息。

要了解更多关于 Timer 类的信息,您可以点击此处查看 Apple 官方文档

https://developer.apple.com/documentation/foundation/timer

为了以固定时间间隔重复执行任务,我们将使用 Timer 类。我们将开发一个示例应用程序,该应用程序每 5 秒打印一次 hello Tutorials Point。

让我们开始吧!

步骤 1 − 打开 Xcode → 新建项目 →单视图应用程序 → 我们将其命名为"HelloTutotrialsPoint"

步骤 2  − 打开 ViewController.swift 并在 ViewDidLoad() 下方编写一个方法 doSomething()。将以下代码复制粘贴到你的 doSomething 方法中。

private func doSomething() {
  let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self,
      selector: #selector(ViewController.hello), userInfo: nil, repeats: true)
}

步骤 3: 如下所示实现/创建 hello (selector),并在 ViewDidLoad() 中调用 doSomething()。

@objc func hello() {
   print("hello")
}

最终代码应如下所示

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
   override func viewDidLoad() {
      super.viewDidLoad()
      // 加载视图后执行任何其他设置,通常从 nib 文件执行。
      self.doSomething()
   }
   private func doSomething() {
      let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self,
      selector: #selector(ViewController.hello), userInfo: nil, repeats: true)
   }
   @objc func hello() {
      print("hello")
   }
}

我们完成了,运行你的应用程序并在控制台中检查输出,你会看到 “hello” 每隔 5 秒打印一次。


相关文章