IOS OC Multi-task timer Nsrunloop management Nstimer

Source: Internet
Author: User

Here are two ways

1. Use the date component nsdatecomponents

2. Use NSString to generate a date

Create a Calendar object

Nscalendar *calendar = [Nscalendar Currentcalendar];

Create a Date component

Nsdatecomponents *DC = [[Nsdatecomponents alloc]init];

Set the current time

[DC Setcalendar:calendar];

[DC setyear:2014];

[DC Setmonth:4];

[DC Setday:9];

[DC sethour:21];

[DC setminute:26];

[DC setsecond:0];

NSString *datestr = @ "2014-04-0921:38:00";

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

[Email protected] "YYYY-MM-DDHH:MM:SS";

NSDate *schudulenate = [DC Date];

NSDate *schudulenate2 = [Formatter datefromstring:datestr];

NSDate *datenow = [NSDate Date];

Calculate Time Difference

Nstimeinterval num = [SchuduleNate2 timeintervalsincedate:datenow];

NSLog (@ "%f to perform the task", NUM);

Task Pool

Nsrunloop *mainloop = [Nsrunloop currentrunloop];

//

Nstimer *timer = [Nstimer scheduledtimerwithtimeinterval:num target:self selector: @selector (scheduleTask) UserInfo: Nil Repeats:no];

Nstimer *timer2 = [Nstimer scheduledtimerwithtimeinterval:num+3 target:self selector: @selector (scheduleTask) userInfo : Nil Repeats:no];

Add to Task Pool

[Mainloop Addtimer:timer Formode:nsdefaultrunloopmode];

[Mainloop Addtimer:timer2 Formode:nsdefaultrunloopmode];

[Mainloop Run];

Output information

2014-04-09 21:37:54.289 wechat[1810:60b] 5.710526 start to perform tasks

2014-04-09 21:38:00.001 wechat[1810:60b] do some thing

2014-04-09 21:38:03.001 wechat[1810:60b] do some thing

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.