Ken Chu
Ken Chu

Reputation: 137

Run code at midnight everyday

I want to update status at midnight everyday. but timer is by interval. how can I set the interval by day

var timer = Timer()

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

// called every time interval from the timer
func timerAction() {

}

Upvotes: 7

Views: 2866

Answers (1)

vadian
vadian

Reputation: 285069

No timer needed. Observe the notification

static let NSCalendarDayChanged: NSNotification.Name

Posted whenever the calendar day of the system changes, as determined by the system calendar, locale, and time zone. This notification does not provide an object.

If the the device is asleep when the day changes, this notification will be posted on wakeup. Only one notification will be posted on wakeup if the device has been asleep for multiple days.

NotificationCenter.default.addObserver(self, selector:#selector(calendarDayDidChange), name:.NSCalendarDayChanged, object:nil)

...

func calendarDayDidChange()
{
    print("day did change")
}

Or with the closure based API

NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object: nil, queue: .main) { _ in
   print("day did change")
}

Or with Combine

var subscription : AnyCancellable?

subscription = NotificationCenter.default.publisher(for: .NSCalendarDayChanged)
    .sink { _ in print("day did change") }

Or with async/await (Swift 5.5+)

Task {
    for await _ in NotificationCenter.default.notifications(named: .NSCalendarDayChanged) {
        print("day did change")
    }
}

Upvotes: 14

Related Questions