在Swift中以随机间隔周期性地调用函数



我试图以随机间隔调用一个函数10次。

我怎样才能做到这一点?

我确实想出了一个方法,但它非常丑陋。它看起来像这样:

    var counter = 0
    NSTimer.scheduledTimerWithTimeInterval(arc4random_uniform(4)+2, target: self, selector: Selector("createNewTimer"), userInfo: nil, repeats: false)
    func createNewTimer(){
    // PERFORM STUFF YOU NEED TO
     counter++
     if counter <= 10{
        NSTimer.scheduledTimerWithTimeInterval(arc4random_uniform(4)+2, target: self, selector: Selector("createNewTimer"), userInfo: nil, repeats: false)
     }
    }

有没有一种更好的方法可以以随机间隔调用函数?

在操场上试试这个。希望能有所帮助:

    func after(delay: Double, block: () -> Void) {
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            block()
        }
    }
    func repeatBlock(counter: Int = 1, times: Int, block: () -> Void) {
        after(Double(arc4random_uniform(4) + 2)) {
            block()
            if counter < times {
                repeatBlock(counter + 1, times: times, block: block)
            }
        }
    }
    //client's code
    var counter = 0
    repeatBlock(times: 10) {
        //your code here
        print(NSDate())
    }
    sleep(100)

如果你需要一个随机区间,那么恐怕以上是最好的解决方案。如果时间间隔相同,则可以将其设置为repeats:true。但不是在你的情况下。

最新更新