首页 > 解决方案 > 如何在特定时间快速运行代码

问题描述

我已经看遍了,但我找不到这个问题的答案。我希望每天早上 6:00 和下午 6:00 在我的应用程序中运行一个特定的功能,以实现日/夜模式。这不需要在后台运行,只需在应用程序打开时运行,但我还想在检查时间时预置应用程序的其他功能。

标签: swift

解决方案


你可以这样做。只需DateCalendar对象设置 a 。将您的特定时间放在军用时间(从 0 到 24,其中 0 是午夜),瞧!如果您的应用程序在前台并且指定时间开始,您将看到您用作选择器执行的函数

试一试,愉快的编码

override func viewDidLoad() {
    super.viewDidLoad()

    let calendar = Calendar.current 

    let now = Date()
    let date = calendar.date(
        bySettingHour: 23,
        minute: 52,
        second: 0,
        of: now)!

    let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)

    RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
}

func runCode() {
    print("Do whatever here")
}

推荐阅读