问题
I would like to run a function (make an api call) at fixed time everyday, say 10 am and 10 pm daily. What would be the cronjob equivalent in swift?
I tried implementing Timer as:
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)
The selector function:
@objc func updateTimer() {
print("Hello")
}
Instead of being run at the specified time, the selector function gets executed everytime I run the app and not at the specified time. How can I solve this?
Edit: I’ll be needing this to be run from the background as well. I’ll be using location service in my app.
回答1:
There is no way to achieve your goals without using push notifications. Timer
's are using run loops and hence aren't working in the background. There's no background mode for making API calls at regular intervals either.
The only option is to send out push notifications from your server at the specified times every day and in response to receiving the push notification in your app, make the API call. Of course you'll need internet connection for push notifications to work, but since you want to make API calls, this won't make a difference as you'd need internet connection for the API calls to succeed anyways.
来源:https://stackoverflow.com/questions/51135941/run-a-task-at-fixed-time-everyday