每天在固定时间运行任务 [英] Run a task at fixed time everyday

查看:58
本文介绍了每天在固定时间运行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每天在固定时间运行一个函数(进行 api 调用),比如每天上午 10 点和晚上 10 点.swift 中的 cronjob 等价物是什么?

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)

选择器函数:

@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?

我也需要它从后台运行.我将在我的应用中使用位置服务.

I’ll be needing this to be run from the background as well. I’ll be using location service in my app.

推荐答案

不使用推送通知就无法实现您的目标.Timer 正在使用运行循环,因此不在后台工作.也没有用于定期进行 API 调用的后台模式.

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.

唯一的选择是在每天的指定时间从您的服务器发送推送通知,并在您的应用程序中收到推送通知后,进行 API 调用.当然,您需要互联网连接才能使推送通知工作,但由于您想要进行 API 调用,因此这不会有什么区别,因为无论如何您都需要互联网连接才能成功调用 API.

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.

这篇关于每天在固定时间运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆