-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWFSparseTimer.m
More file actions
111 lines (96 loc) · 2.61 KB
/
WFSparseTimer.m
File metadata and controls
111 lines (96 loc) · 2.61 KB
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
//
// WFSparseTimer.m
//
// Created by Jesper on 2011-03-06.
//
// The contents of this file is placed in the public domain.
// No rights are reserved, asserted or exercised.
// For more information, see:
// http://creativecommons.org/publicdomain/zero/1.0/
//
#import "WFSparseTimer.h"
//#define WFSparseTimerTracing 1
@implementation WFSparseTimer
- (id)initWithDispatchQueue:(dispatch_queue_t)aQueue
atRoughInterval:(NSTimeInterval)interval
block:(dispatch_block_t)aBlock
{
self = [super init];
if (self) {
blockQueue = aQueue;
dispatch_retain(blockQueue);
controlQueue = dispatch_queue_create([[NSString stringWithFormat:@"WFSparseTimer %p control queue", self] UTF8String], 0);
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, controlQueue);
dispatch_source_set_timer(source, dispatch_walltime(NULL, 0), interval * NSEC_PER_SEC, 0.005 * NSEC_PER_SEC);
block = [aBlock copy];
dispatch_source_set_event_handler(source, ^() {
if (shouldFire) {
shouldFire = NO;
#ifdef WFSparseTimerTracing
NSLog(@"#%@ firing", self);
#endif
dispatch_suspend(source);
dispatch_sync(blockQueue, block);
} else {
#ifdef WFSparseTimerTracing
NSLog(@"#%@ not firing", self);
#endif
}
});
}
return self;
}
- (void)setNeedsFire {
if (source == NULL)
[NSException raise:@"WFSparseTimer made to fire after being invalidated." format:@""];
dispatch_async(controlQueue, ^{
if (source == NULL)
return;
if (!shouldFire) {
dispatch_resume(source);
}
shouldFire = YES;
#ifdef WFSparseTimerTracing
NSLog(@"#%@ needs to fire", self);
#endif
});
}
- (void)toss {
if (tossed) return;
tossed = YES;
shouldFire = NO;
dispatch_async(controlQueue, ^{
#ifdef WFSparseTimerTracing
NSLog(@"#%@ tossed", self);
#endif
dispatch_source_cancel(source);
dispatch_release(source);
if (shouldFire) {
dispatch_resume(controlQueue);
}
dispatch_release(controlQueue);
dispatch_release(blockQueue);
[block release];
source = NULL;
});
}
- (void)invalidate {
[self toss];
[self autorelease];
}
- (BOOL)isValid {
return (source != NULL);
}
-(void)finalize {
if (source != NULL) {
[self toss];
}
[super finalize];
}
- (void)dealloc {
if (source != NULL) {
[self toss];
}
[super dealloc];
}
@end