Scheduled tasks and IOS tasks in IOS

Source: Internet
Author: User

Scheduled tasks and IOS tasks in IOS

NSTimer allows you to set scheduled tasks in the APP. You can use setKeepAliveTimeout: handler to set scheduled tasks when the APP is running in the background.

NSTimer

The following is the NSTimer header file, which describes methods such as timerWithTimeInterval, scheduledTimerWithTimeInterval, initWithFireDate, fire, and invalidate.
You can use the fire method to immediately trigger the Timer:
1. using fire in repeated scheduled tasks can immediately trigger the task without interrupting its previous scheduled task.
2. Use fire to immediately trigger the task in a one-time scheduled task, but the timer immediately fails.
The invalidate method is the only method that can remove a timer from the runloop.

/*  NSTimer.h    Copyright (c) 1994-2014, Apple Inc. All rights reserved.*/#import <Foundation/NSObject.h>#import <Foundation/NSDate.h>@interface NSTimer : NSObject+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep NS_DESIGNATED_INITIALIZER;- (void)fire;@property (copy) NSDate *fireDate;@property (readonly) NSTimeInterval timeInterval;// Setting a tolerance for a timer allows it to fire later than the scheduled fire date, improving the ability of the system to optimize for increased power savings and responsiveness. The timer may fire at any time between its scheduled fire date and the scheduled fire date plus the tolerance. The timer will not fire before the scheduled fire date. For repeating timers, the next fire date is calculated from the original fire date regardless of tolerance applied at individual fire times, to avoid drift. The default value is zero, which means no additional tolerance is applied. The system reserves the right to apply a small amount of tolerance to certain timers regardless of the value of this property.// As the user of the timer, you will have the best idea of what an appropriate tolerance for a timer may be. A general rule of thumb, though, is to set the tolerance to at least 10% of the interval, for a repeating timer. Even a small amount of tolerance will have a significant positive impact on the power usage of your application. The system may put a maximum value of the tolerance.@property NSTimeInterval tolerance NS_AVAILABLE(10_9, 7_0);- (void)invalidate;@property (readonly, getter=isValid) BOOL valid;@property (readonly, retain) id userInfo;@end
Use instance

To add a scheduled task for the following instance, periodically execute a POST request to report the device power information to the specified API.

const NSString *batteryLevelURL = @"http://localhost/batteryLevel/level";- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    [self reportDeviceInfo];    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:100 target:self             selector:@selector(reportDeviceInfo) userInfo:nil repeats:true];}-(void) reportDeviceInfo {    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    [manager POST:batteryLevelURL parameters:[self getDeviceInfo]        success:^(AFHTTPRequestOperation *operation, id responseObject) {            NSLog(@"succeed in reporting device info.");            self.networkLabel.textColor = UIColor.blackColor;            self.networkLabel.text = @"Succeed in reporting this device info.";        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {            NSLog(@"fail to report device info.");            self.networkLabel.textColor = UIColor.redColor;            self.networkLabel.text = @"Fail to report device info. please check network.";        }];}

ScheduledTimerWithTimeInterval is used to set the repeated tasks scheduled to be executed.
The main parameter is the interval and the scheduled execution function selector: @ selector (reportDeviceInfo ).

Scheduled execution in the background

The timer task that uses NSTimer can only be executed on the foreground. Once the APP enters the background, the timer cannot work normally.
If you want to perform scheduled tasks in the background, you need to do the following:
1. Add the UIBackgroundModes attribute to Info. plist, that is, Required background modes, and add VOIP, audio, location, Bluetooth, and download.
2. Use the setKeepAliveTimeout: handler: Method to register a periodically executed task, regardless of whether it is running in the background.

- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    [self reportDeviceInfo];    [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{[self reportDeviceInfo];}];}

If the APP runs in the background, the reportDeviceInfo () method is still called periodically.
ClearKeepAliveTimeout can be used to clear the scheduled task accordingly.

- (BOOL)setKeepAliveTimeout:(NSTimeInterval)timeout handler:(void(^)(void))keepAliveHandler NS_AVAILABLE_IOS(4_0);- (void)clearKeepAliveTimeout NS_AVAILABLE_IOS(4_0);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.