/
EDQueue.m
executable file
·259 lines (226 loc) · 6.8 KB
/
EDQueue.m
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//
// EDQueue.m
// queue
//
// Created by Andrew Sliwinski on 6/29/12.
// Copyright (c) 2012 Andrew Sliwinski. All rights reserved.
//
#import "EDQueue.h"
#import "EDQueueStorageEngine.h"
NSString *const EDQueueDidStart = @"EDQueueDidStart";
NSString *const EDQueueDidStop = @"EDQueueDidStop";
NSString *const EDQueueJobDidSucceed = @"EDQueueJobDidSucceed";
NSString *const EDQueueJobDidFail = @"EDQueueJobDidFail";
NSString *const EDQueueDidDrain = @"EDQueueDidDrain";
@interface EDQueue ()
{
BOOL _isRunning;
BOOL _isActive;
NSUInteger _retryLimit;
}
@property (nonatomic) EDQueueStorageEngine *engine;
@property (nonatomic, readwrite) NSString *activeTask;
@end
//
@implementation EDQueue
@synthesize isRunning = _isRunning;
@synthesize isActive = _isActive;
@synthesize retryLimit = _retryLimit;
#pragma mark - Singleton
+ (EDQueue *)sharedInstance
{
static EDQueue *singleton = nil;
static dispatch_once_t once = 0;
dispatch_once(&once, ^{
singleton = [[self alloc] init];
});
return singleton;
}
#pragma mark - Init
- (id)init
{
self = [super init];
if (self) {
_engine = [[EDQueueStorageEngine alloc] init];
_retryLimit = 4;
}
return self;
}
- (void)dealloc
{
self.delegate = nil;
_engine = nil;
}
#pragma mark - Public methods
/**
* Adds a new job to the queue.
*
* @param {id} Data
* @param {NSString} Task label
*
* @return {void}
*/
- (void)enqueueWithData:(id)data forTask:(NSString *)task
{
if (data == nil) data = @{};
[self.engine createJob:data forTask:task];
[self tick];
}
/**
* Returns true if a job exists for this task.
*
* @param {NSString} Task label
*
* @return {Boolean}
*/
- (BOOL)jobExistsForTask:(NSString *)task
{
BOOL jobExists = [self.engine jobExistsForTask:task];
return jobExists;
}
/**
* Returns true if the active job if for this task.
*
* @param {NSString} Task label
*
* @return {Boolean}
*/
- (BOOL)jobIsActiveForTask:(NSString *)task
{
BOOL jobIsActive = [self.activeTask length] > 0 && [self.activeTask isEqualToString:task];
return jobIsActive;
}
/**
* Returns the list of jobs for this
*
* @param {NSString} Task label
*
* @return {NSArray}
*/
- (NSDictionary *)nextJobForTask:(NSString *)task
{
NSDictionary *nextJobForTask = [self.engine fetchJobForTask:task];
return nextJobForTask;
}
/**
* Starts the queue.
*
* @return {void}
*/
- (void)start
{
if (!self.isRunning) {
_isRunning = YES;
[self tick];
[self performSelectorOnMainThread:@selector(postNotification:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:EDQueueDidStart, @"name", nil, @"data", nil] waitUntilDone:false];
}
}
/**
* Stops the queue.
* @note Jobs that have already started will continue to process even after stop has been called.
*
* @return {void}
*/
- (void)stop
{
if (self.isRunning) {
_isRunning = YES;
[self performSelectorOnMainThread:@selector(postNotification:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:EDQueueDidStop, @"name", nil, @"data", nil] waitUntilDone:false];
}
}
/**
* Empties the queue.
* @note Jobs that have already started will continue to process even after empty has been called.
*
* @return {void}
*/
- (void)empty
{
[self.engine removeAllJobs];
}
#pragma mark - Private methods
/**
* Checks the queue for available jobs, sends them to the processor delegate, and then handles the response.
*
* @return {void}
*/
- (void)tick
{
dispatch_queue_t gcd = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(gcd, ^{
if (self.isRunning && !self.isActive && [self.engine fetchJobCount] > 0) {
// Start job
_isActive = YES;
id job = [self.engine fetchJob];
self.activeTask = [(NSDictionary *)job objectForKey:@"task"];
// Pass job to delegate
if ([self.delegate respondsToSelector:@selector(queue:processJob:completion:)]) {
[self.delegate queue:self processJob:job completion:^(EDQueueResult result) {
[self processJob:job withResult:result];
self.activeTask = nil;
}];
} else {
EDQueueResult result = [self.delegate queue:self processJob:job];
[self processJob:job withResult:result];
self.activeTask = nil;
}
}
});
}
- (void)processJob:(NSDictionary*)job withResult:(EDQueueResult)result
{
// Check result
switch (result) {
case EDQueueResultSuccess:
[self performSelectorOnMainThread:@selector(postNotification:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:EDQueueJobDidSucceed, @"name", job, @"data", nil] waitUntilDone:false];
[self.engine removeJob:[job objectForKey:@"id"]];
break;
case EDQueueResultFail:
[self performSelectorOnMainThread:@selector(postNotification:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:EDQueueJobDidFail, @"name", job, @"data", nil] waitUntilDone:true];
NSUInteger currentAttempt = [[job objectForKey:@"attempts"] intValue] + 1;
if (currentAttempt < self.retryLimit) {
[self.engine incrementAttemptForJob:[job objectForKey:@"id"]];
} else {
[self.engine removeJob:[job objectForKey:@"id"]];
}
break;
case EDQueueResultCritical:
[self performSelectorOnMainThread:@selector(postNotification:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:EDQueueJobDidFail, @"name", job, @"data", nil] waitUntilDone:false];
[self errorWithMessage:@"Critical error. Job canceled."];
[self.engine removeJob:[job objectForKey:@"id"]];
break;
}
// Clean-up
_isActive = NO;
// Drain
if ([self.engine fetchJobCount] == 0) {
[self performSelectorOnMainThread:@selector(postNotification:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:EDQueueDidDrain, @"name", nil, @"data", nil] waitUntilDone:false];
} else {
[self performSelectorOnMainThread:@selector(tick) withObject:nil waitUntilDone:false];
}
}
/**
* Posts a notification (used to keep notifications on the main thread).
*
* @param {NSDictionary} Object
* - name: Notification name
* - data: Data to be attached to notification
*
* @return {void}
*/
- (void)postNotification:(NSDictionary *)object
{
[[NSNotificationCenter defaultCenter] postNotificationName:[object objectForKey:@"name"] object:[object objectForKey:@"data"]];
}
/**
* Writes an error message to the log.
*
* @param {NSString} Message
*
* @return {void}
*/
- (void)errorWithMessage:(NSString *)message
{
NSLog(@"EDQueue Error: %@", message);
}
@end