这段代码可以放在- (void)applicationWillResignActive:(UIApplication *)application或者- (void)applicationDidEnterBackground:(UIApplication *)application
中,当然,当程序重新被激活的时候,需要将timer invalidate掉。
中,当然,当程序重新被激活的时候,需要将timer invalidate掉。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
UIApplication
*app = [
UIApplication
sharedApplication
];
__block
UIBackgroundTaskIdentifier
bgTask = [app
beginBackgroundTaskWithExpirationHandler
:^{
dispatch_async(dispatch_get_main_queue(), ^{
if
(bgTask != UIBackgroundTaskInvalid) {
[app
endBackgroundTask
:bgTask];
bgTask =
UIBackgroundTaskInvalid
;
}
});
}];
dispatch_async(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT
,
0
), ^{
testTimer = [
NSTimer
scheduledTimerWithTimeInterval
:(
0
.01
)
target
:
self
selector
:
@selector
(doSomeTest)
userInfo
:nil
repeats
:
YES
];
[testTimer
fire
];
[[
NSRunLoop
currentRunLoop
]
addTimer
:testTimer
forMode
:NSRunLoopCommonModes];
[[
NSRunLoop
currentRunLoop
]
run
];
dispatch_async(dispatch_get_main_queue(), ^{
if
(bgTask != UIBackgroundTaskInvalid) {
[app
endBackgroundTask
:bgTask];
bgTask =
UIBackgroundTaskInvalid
;
}
});
});
|
Tag : NSTimer , background task , 后台运行