2 // HMPeriodicNotifier.m
5 // Created by Hori,Masaki on 2015/06/13.
6 // Copyright (c) 2015年 Hori,Masaki. All rights reserved.
9 #import "HMPeriodicNotifier.h"
12 NSString *HMPeriodicNotification = @"HMPeriodicNotification";
14 @interface HMPeriodicNotifier ()
15 @property NSUInteger hour;
16 @property NSUInteger minutes;
18 @property (strong, nonatomic) NSDateComponents *currentDay;
19 @property (strong, nonatomic) NSTimer *timer;
22 @implementation HMPeriodicNotifier
24 + (instancetype)periodicNotifierWithHour:(NSUInteger)hour minutes:(NSUInteger)minutes
26 return [[self alloc] initWithHour:hour minutes:minutes];
28 - (instancetype)initWithHour:(NSUInteger)hour minutes:(NSUInteger)minutes
34 [self registerNotifications];
35 [self notifyIfNeeded:nil];
40 - (void)registerNotifications
42 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
45 selector:@selector(notifyIfNeeded:)
46 name:NSSystemTimeZoneDidChangeNotification
49 selector:@selector(notifyIfNeeded:)
50 name:NSSystemClockDidChangeNotification
53 selector:@selector(notifyIfNeeded:)
54 name:NSWorkspaceDidWakeNotification
58 - (void)notifyIfNeeded:(id)timer
60 NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0.0];
61 NSCalendarUnit unit = NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
62 NSDateComponents *currentDay = [[NSCalendar currentCalendar] components:unit fromDate:now];
63 currentDay.hour = self.hour;
64 currentDay.minute = self.minutes;
65 NSDate *notifyDate = [[NSCalendar currentCalendar] dateFromComponents:currentDay];
67 if([now compare:notifyDate] == NSOrderedDescending) {
69 [[NSNotificationCenter defaultCenter] postNotificationName:HMPeriodicNotification
73 if(self.timer.valid) {
74 [self.timer invalidate];
77 NSDate *nextNotifyDate = [[NSCalendar currentCalendar] dateFromComponents:currentDay];
78 NSTimeInterval nextNotifyTime = [nextNotifyDate timeIntervalSinceNow];
80 self.timer = [NSTimer scheduledTimerWithTimeInterval:nextNotifyTime + 0.1