2016-09-19 44 views
-3

我试图找到在Swift中创建预定任务的最佳方式,但是我发现所有的代码都是过时的代码和Objective-C代码。我想知道你们是如何在最新版本的Swift中做到这一点的。在Swift中创建预定堆栈的最佳方法

感谢

+0

可能的重复http://stackoverflow.com/questions/24007518/how-can-i-use-nstimer-in-swift – Moritz

回答

0

创建一个将每X秒计时器叫:

// 1: Declare the timer 
var timer = Timer() 

// 2 create your timer as you want it 
    timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(task), userInfo: nil, repeats: true) 

func task(){ 
    // Do something in here 
    print("Called!") 
} 

编辑

// 4 stop it when you want 
timer.invalidate() 

这将调用task()每60秒。你当然可以修改秒。

+0

选择器和目标参数有什么区别 – Pablo

+0

'选择器'是你的方法想要调用,当定时器触发时,“taget”是发送由aSelector指定的消息的对象。定时器保持对目标的强引用,直到它(定时器)失效。 –

+0

@Pablo,上面的解决方案是否适合您? –