Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code at midnight everyday

Tags:

macos

swift

timer

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() {

}
like image 421
Ken Chu Avatar asked Jul 18 '26 16:07

Ken Chu


1 Answers

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")
    }
}
like image 149
vadian Avatar answered Jul 21 '26 04:07

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!