在Swift中将后台任务作为循环运行

编程入门 行业动态 更新时间:2024-10-09 14:25:28
本文介绍了在Swift中将后台任务作为循环运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道我可以创建这样的后台任务:

I know that I can create a background task like this:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // do some task dispatch_async(dispatch_get_main_queue(), ^{ // update some UI }); });

(来源)

如何创建一个后台任务,每个 n执行代码块秒,如何停止此任务?

How can I create a background task which executes a code block every n seconds and how can I stop this task?

推荐答案

结合 NSTimer 和您的背景代码。这将是:

Combine NSTimer and your background code. That will be like:

- (void)someBackgroundTask:(NSTimer *)timer { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // do some task dispatch_async(dispatch_get_main_queue(), ^{ // update some UI }); }); }

然后通过计时器调用此方法

and then call this method through timer

NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(someBackgroundTask:) userInfo:nil repeats:YES];

停止该计时器和后台执行

to stop that timer and the background execution

[timer invalidate];

func someBackgroundTask(timer:NSTimer) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in println("do some background task") dispatch_async(dispatch_get_main_queue(), { () -> Void in println("update some UI") }) }) }

然后通过计时器调用此方法

and then call this method through timer

var timer = NSTimer(timeInterval: 1.0, target: self, selector: "someBackgroundTask:", userInfo: nil, repeats: true)

停止该计时器和后台执行

to stop that timer and the background execution

timer.invalidate()

Swift 3及更高版本

Swift 3 and later

func someBackgroundTask(timer:Timer) { DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { print("do some background task") DispatchQueue.main.async { print("update some UI") } } }

并创建/调用计时器

var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in self.someBackgroundTask(timer: timer) }

invalidate 方法相同。

更多推荐

在Swift中将后台任务作为循环运行

本文发布于:2023-10-12 16:20:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485256.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   后台   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!