How can I run code block in background periodically using GCD?

后端 未结 3 1939
执念已碎
执念已碎 2021-02-08 05:55

How can I run code block in background periodically using GCD? I am trying to write a game engine with several subsystems, like rendering, physics, game logic and so on. Some ta

3条回答
  •  忘掉有多难
    2021-02-08 06:27

    In Swift you can create timer using GCD:

    func CreateTimerDispatchSource(interval: UInt64, leeway: UInt64, queue: dispatch_queue_t, block: dispatch_block_t) -> dispatch_source_t {
        let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
        dispatch_source_set_timer(timer, dispatch_walltime(nil, 0), interval, leeway)
        dispatch_source_set_event_handler(timer, block)
        return timer;
    }
    
    var timer = CreateTimerDispatchSource(5*NSEC_PER_SEC, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
      // do some serious stuff
    }
    

    Start or resume timer:

    dispatch_resume(timer)
    

    Suspend timer:

    dispatch_suspend(timer)
    

提交回复
热议问题