Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer run every minute but on first second

I have experience with NSTimer to run it once per minute, like

NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: Selector("everyMinute"), userInfo: nil, repeats: true)

Is it possible to use NSTimer, some other class, or some other control, to run some method every minute but on first second of minute ?

I do have some idea how to implement it on my own, but I am first checking is this already exist ?

like image 661
WebOrCode Avatar asked Dec 09 '22 05:12

WebOrCode


2 Answers

One way would be to figure out the current next minute using an NSCalendar and schedule the timer to start from that, manually scheduling on the runLoop

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitEra|NSCalendarUnit.CalendarUnitYear|NSCalendarUnit.CalendarUnitMonth|NSCalendarUnit.CalendarUnitDay|NSCalendarUnit.CalendarUnitHour|NSCalendarUnit.CalendarUnitMinute, fromDate: date)
components.minute += 1
components.second = 1
let nextMinuteDate = calendar.dateFromComponents(components)
let timer = NSTimer(fireDate: nextMinuteDate!, interval: 60, target: self, selector: Selector("everyMinute"), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
like image 154
Fabio Ritrovato Avatar answered Dec 10 '22 18:12

Fabio Ritrovato


The accepted answer, updated for Swift 5:

let date = Date()
let calendar = Calendar.current
var components = calendar.dateComponents([.era, .year, .month, .day, .hour, .minute], from: date)

guard let minute = components.minute else { return }
components.second = 0
components.minute = minute + 1

guard let nextMinute = calendar.date(from: components) else { return }

let timer = Timer(fire: nextMinute, interval: 60, repeats: true) { [weak self] timer in
    self?.everyMinute()
}
RunLoop.main.add(timer, forMode: .default)
like image 38
Learn OpenGL ES Avatar answered Dec 10 '22 19:12

Learn OpenGL ES