wxr
2021-07-01 43b0d5870d528f23ecd6aeceb6cfd4325188b46f
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
60
61
62
63
64
65
66
67
//
//  ReconnectTimer.m
//  MQTTClient
//
//  Created by Josip Cavar on 22/08/2017.
//  Copyright © 2017 Christoph Krey. All rights reserved.
//
 
#import "ReconnectTimer.h"
#import "GCDTimer.h"
 
@interface ReconnectTimer()
 
@property (strong, nonatomic) GCDTimer *timer;
@property (assign, nonatomic) NSTimeInterval retryInterval;
@property (assign, nonatomic) NSTimeInterval currentRetryInterval;
@property (assign, nonatomic) NSTimeInterval maxRetryInterval;
@property (strong, nonatomic) dispatch_queue_t queue;
@property (copy, nonatomic) void (^reconnectBlock)(void);
 
@end
 
@implementation ReconnectTimer
 
- (instancetype)initWithRetryInterval:(NSTimeInterval)retryInterval
                     maxRetryInterval:(NSTimeInterval)maxRetryInterval
                                queue:(dispatch_queue_t)queue
                       reconnectBlock:(void (^)(void))block {
    self = [super init];
    if (self) {
        self.retryInterval = retryInterval;
        self.currentRetryInterval = retryInterval;
        self.maxRetryInterval = maxRetryInterval;
        self.reconnectBlock = block;
        self.queue = queue;
    }
    return self;
}
 
- (void)schedule {
    __weak typeof(self) weakSelf = self;
    self.timer = [GCDTimer scheduledTimerWithTimeInterval:self.currentRetryInterval
                                                  repeats:NO
                                                    queue:self.queue
                                                    block:^{
                                                        [weakSelf reconnect];
                                                    }];
}
 
- (void)stop {
    [self.timer invalidate];
    self.timer = nil;
}
 
- (void)resetRetryInterval {
    self.currentRetryInterval = self.retryInterval;
}
 
- (void)reconnect {
    [self stop];
    if (self.currentRetryInterval < self.maxRetryInterval) {
        self.currentRetryInterval *= 2;
    }
    self.reconnectBlock();
}
 
@end