2 // PeriodicNotifier.swift
5 // Created by Hori,Masaki on 2017/01/03.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
11 extension Notification.Name {
13 static let Periodic = Notification.Name("com.masakih.KCD.Notification.Periodic")
16 final class PeriodicNotifier: NSObject {
19 private let minutes: Int
21 init(hour: Int, minutes: Int) {
24 self.minutes = minutes
28 let nc = NotificationCenter.default
29 nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: notify)
30 nc.addObserver(forName: .NSSystemClockDidChange, object: nil, queue: nil, using: notify)
31 NSWorkspace.shared.notificationCenter
32 .addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: nil, using: notify)
35 private func notify(_ notification: Notification) {
40 @objc private func notifyIfNeeded(_ timer: Timer?) {
42 let now = Date(timeIntervalSinceNow: 0.0)
43 var currentDay = Calendar.current.dateComponents([.era, .year, .month, .day], from: now)
44 currentDay.hour = hour
45 currentDay.minute = minutes
47 if let notifyDate = Calendar.current.date(from: currentDay),
48 now.compare(notifyDate) == .orderedDescending {
51 NotificationCenter.default.post(name: .Periodic, object: self)
56 guard let nextNotifyDate = Calendar.current.date(from: currentDay) else {
58 Logger.shared.log("Can not create time of notify")
63 Timer.scheduledTimer(timeInterval: nextNotifyDate.timeIntervalSinceNow + 0.1,
65 selector: #selector(PeriodicNotifier.notifyIfNeeded(_:)),