2017-05-26 37 views
0

我只是想知道什么是最好的实施内存优化多功能多计时器在迅速。 定时器是并发并有弱参考与调度? 我试图在一个视图控制器中实现两个定时器,并且出现错误。如何在swift中实现优化多重定时器?

我的计时器之一是这样的:

func startOnPlayingTimer() { 

let queue = DispatchQueue(label: "com.app.timer") 
onPlayTimer = DispatchSource.makeTimerSource(queue: queue) 
onPlayTimer!.scheduleRepeating(deadline: .now(), interval: .seconds(4)) 
onPlayTimer!.setEventHandler { [weak self] in 
    print("onPlayTimer has triggered") 
} 
onPlayTimer!.resume() 
} 

另一个是:

carouselTimer = Timer.scheduledTimer(timeInterval: 3, target: self,selector: #selector(scrollCarousel), userInfo: nil, repeats: true) 
+1

我只会创建多个'Timer'实例。你遇到了什么错误? – Paulw11

+0

@ Paulw11其实,我今天可以用'Timer'实现这个。但我怀疑这个函数线程安全吗?并有一个“弱参考”?我正在寻找与Dispatch实现这一点,并使其线程安全和内存优化。 – Omnia

+0

线程安全和cicrcular强引用是计时器的单独问题。没有计时器方法会给你固有的线程安全。线程的安全性取决于你在由定时器调度的闭包中做什么。定时器可以对能源使用产生影响,事实上苹果公司特别建议不要将定时器用作同步技术; https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/MinimizeTimerUse.html。您仍然没有解释当您尝试使用两个定时器时出现的“错误”错误 – Paulw11

回答

0

我不认为有必要为任何应用程序的多个计时器。 如果来自以前知道要触发哪种方法,请为每个需要触发的方法保留布尔值,并保存方法的出现。您可以调用一次定时器,并使用一种方法来检查所需的布尔值及其各自的方法。

的伪代码引用了上面的逻辑是以下:

class ViewController: UIViewController { 


var myTimer : Timer! 

var methodOneBool : Bool! 
var methodTwoBool : Bool! 
var mainTimerOn : Bool! 


var mainTimerLoop : Int! 
var methodOneInvocation : Int! 
var methodTwoInvocation : Int! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    configure() 
} 

func configure(){ 
    methodOneBool = false 
    methodTwoBool = false 

    methodOneInvocation = 5 // every 5 seconds 
    methodTwoInvocation = 3 //every 3 seconds 

    mainTimerOn = true // for disable and enable timer 
    mainTimerLoop = 0 // count for timer main 
} 

func invokeTimer(){ 
    myTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(checkTimerMethod), userInfo: nil, repeats: true) 
} 


func checkTimerMethod(){ 

    if(mainTimerOn){ 

     if(mainTimerLoop % methodOneInvocation == 0 && methodOneBool){ 
      // perform first method 
      // will only get inside this when 
      // methodOneBool = true and every methodOneInvocation seconds 
     } 

     if(mainTimerLoop % methodTwoInvocation == 0 && methodTwoBool){ 
      // perform second method 
      // will only get inside this when 
      // methodTwoBool = true and every methodTwoInvocation seconds 
     } 

     mainTimerLoop = mainTimerLoop + 1 

    } 
} 

} 

我希望这清除了问题,另外,如果我不明白您的要求,请评论下面,这样我就可以相应地编辑答案

+1

国际海事组织它是简单得多,只是有两个计时器 – Paulw11

+0

计时器是非常沉重的对象,并需要大量的内存来调用AFAIK,所以它尽量少维护 –

+0

。一旦确定存在问题,请始终选择最简单的解决方案并在必要时进行优化。你的解决方案有更多的“移动部件”,因此有潜在的错误 – Paulw11