运行每天定时任务
Run a task at fixed time everyday
我想在每天固定的时间 运行 执行一个功能(进行 api 调用),比如每天上午 10 点和晚上 10 点。 swift 中的 cronjob 等价物是什么?
我尝试将 Timer 实现为:
var dateComponents = DateComponents()
dateComponents.timeZone = TimeZone(abbreviation: "NPT")
dateComponents.hour = 10
dateComponents.minute = 00
let userCalendar = Calendar.current
let myTime = userCalendar.date(from: dateComponents)
let timer = Timer(fireAt: myTime!, interval: 0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
选择器函数:
@objc func updateTimer() {
print("Hello")
}
选择器函数不是在指定时间 运行 而是在每次 运行 应用程序时执行,而不是在指定时间执行。我该如何解决?
编辑:我也需要 运行 从后台进行。我将在我的应用中使用定位服务。
不使用推送通知就无法实现您的目标。 Timer
正在使用 运行 循环,因此无法在后台运行。也没有定期进行 API 调用的后台模式。
唯一的选择是每天在指定时间从您的服务器发送推送通知,并响应在您的应用程序中收到推送通知,进行 API 调用。当然,您需要互联网连接才能使推送通知正常工作,但由于您要拨打 API 电话,这不会有什么不同,因为您需要互联网连接才能拨打 API无论如何都要成功。
我想在每天固定的时间 运行 执行一个功能(进行 api 调用),比如每天上午 10 点和晚上 10 点。 swift 中的 cronjob 等价物是什么?
我尝试将 Timer 实现为:
var dateComponents = DateComponents()
dateComponents.timeZone = TimeZone(abbreviation: "NPT")
dateComponents.hour = 10
dateComponents.minute = 00
let userCalendar = Calendar.current
let myTime = userCalendar.date(from: dateComponents)
let timer = Timer(fireAt: myTime!, interval: 0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
选择器函数:
@objc func updateTimer() {
print("Hello")
}
选择器函数不是在指定时间 运行 而是在每次 运行 应用程序时执行,而不是在指定时间执行。我该如何解决?
编辑:我也需要 运行 从后台进行。我将在我的应用中使用定位服务。
不使用推送通知就无法实现您的目标。 Timer
正在使用 运行 循环,因此无法在后台运行。也没有定期进行 API 调用的后台模式。
唯一的选择是每天在指定时间从您的服务器发送推送通知,并响应在您的应用程序中收到推送通知,进行 API 调用。当然,您需要互联网连接才能使推送通知正常工作,但由于您要拨打 API 电话,这不会有什么不同,因为您需要互联网连接才能拨打 API无论如何都要成功。