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 ?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With