1
wei
2021-01-21 62d098cb78296feaa6f786a20748921338db838c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
//  Timer.m
//  MQTTClient
//
//  Created by Josip Cavar on 06/11/2017.
//  Copyright © 2017 Christoph Krey. All rights reserved.
//
 
#import "GCDTimer.h"
 
@interface GCDTimer ()
 
@property (strong, nonatomic) dispatch_source_t timer;
 
@end
 
@implementation GCDTimer
 
+ (GCDTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                     repeats:(BOOL)repeats
                                       queue:(dispatch_queue_t)queue
                                       block:(void (^)(void))block {
    GCDTimer *timer = [[GCDTimer alloc] initWithInterval:interval
                                                 repeats:repeats
                                                   queue:queue
                                                   block:block];
    return timer;
}
 
- (instancetype)initWithInterval:(NSTimeInterval)interval
                         repeats:(BOOL)repeats
                           queue:(dispatch_queue_t)queue
                           block:(void (^)(void))block {
    self = [super init];
    if (self) {
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, interval * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(self.timer, ^{
            if (!repeats) {
                dispatch_source_cancel(self.timer);
            }
            block();
        });
        dispatch_resume(self.timer);
    }
    return self;
}
 
- (void)dealloc {
    [self invalidate];
}
 
- (void)invalidate {
    if (self.timer) {
        dispatch_source_cancel(self.timer);
    }
}
 
@end