Timed tasks in iOS

Source: Internet
Author: User

Nstimer can set tasks that are scheduled to be performed in the app. Instead, use Setkeepalivetimeout:handler: You can set up timed tasks when the app is running in the background.

Nstimer

Below is Nstimer's head file, which introduces Timerwithtimeinterval, Scheduledtimerwithtimeinterval, Initwithfiredate, fire, invalidate and other methods.
Use the fire method to trigger the timer immediately:
1. Using fire in recurring scheduled tasks can immediately trigger a task without interrupting its previous scheduled schedule.
2. Use fire to trigger a task immediately 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 forA timer allows it toFire later than the scheduled fire date, improving the ability ofThe system toOptimize forIncreased power savings andResponsiveness. The timer may fire at any TimeBetween its scheduled fire date andThe scheduled fire date plus the tolerance. The timer would notFire before the scheduled fire date. forRepeating timers, theNextFire Date isCalculated from the original fire date regardless ofTolerance applied at the individual fire times, toAvoid drift. ThedefaultValue isZero, which means no additional tolerance isApplied. The System reserves the right toApply a small amount ofTolerance toCertain timers regardless ofThe value ofThis Property.//As the user ofThe timer, you'll have the ofWhat's an appropriate tolerance forA timer May. A general rule ofThumb, though, is  toSet the tolerance toAt leastTen% ofThe interval, forA repeating timer. Even a small amount ofTolerance would have a significantPositiveImpact onThe Power usage ofYour application. The system may put a maximum value ofThe tolerance.@ PropertyNstimeinterval Tolerance ns_available (Ten_9,7_0);-(void) invalidate;@ Property(ReadOnly, Getter=isvalid) BOOL valid;@ Property(ReadOnly, retain) ID userinfo;@End
Working with instances

The use instance below adds a timed task that periodically executes a POST request to report the device power information to the specified API.

Const NSString*batterylevelurl = @"Http://localhost/batteryLevel/level";- (void) Viewdidload {[SuperViewdidload];additional setup after loading the view, typically from a nib.[ SelfReportdeviceinfo]; Nstimer *timer = [Nstimer scheduledtimerwithtimeinterval: -Target SelfSelector@selector(Reportdeviceinfo) UserInfo:NilRepeatstrue];} -(void) Reportdeviceinfo {Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager]; [Manager Post:batterylevelurl parameters:[ SelfGetdeviceinfo] success:^ (afhttprequestoperation *operation,IDResponseobject) {NSLog(@"Succeed in reporting device info."); Self. Networklabel. TextColor=Uicolor. Blackcolor; Self. Networklabel. Text= @"Succeed in reporting the" 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 the network. "; }];}

Where Scheduledtimerwithtimeinterval is used to set the recurring task to be performed at timed intervals.
The main parameters are the interval time, and the function of the timed execution selector: @selector (reportdeviceinfo).

Background timed execution

The timer task using Nstimer can only be performed in the foreground, which will not work once the app enters the background.
If you need to perform a timed task in the background, you need to do two points:
1. Add Uibackgroundmodes attribute in Info.plist, i.e. required background modes, add VoIP, audio, location, bluetooth, download, etc.
2. Use the Setkeepalivetimeout:handler: method to register a recurring 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];}];}

At this point, if the app is running in the background, the Reportdeviceinfo () method will still be called periodically.
You can use Clearkeepalivetimeout 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);

Timed tasks in iOS

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.