在Swift中将后台任务作为循环运行 [英] Run Background Task as Loop in Swift

查看:506
本文介绍了在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中将后台任务作为循环运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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