2014-06-12 2 views
0

매분 호출 될 함수를 만들려고했습니다 (이없는 ).
앱을 실행하면 1 분 후에 다시 실행됩니다.
나는 아마 뭔가를 놓치지 만 무엇을 찾을 수 없습니까?
IOS에서 함수 호출을 두 번 이상 실행할 수 없습니다.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    NSDate *date = [NSDate date]; 
    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSSecondCalendarUnit fromDate:date]; 

    NSTimeInterval timeSinceLastSecond = date.timeIntervalSince1970 - floor(date.timeIntervalSince1970); 
    NSTimeInterval timeToNextMinute = (60 - dateComponents.second) - timeSinceLastSecond; 

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeToNextMinute * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 

     [self myFunction]; 

    }); 

    return YES; 
} 
+0

조금 혼란 스러워요! dispatch_after가 간격을두고 반복하지 않고 시간에 따라 실행을 지연시키지 않습니까? –

+0

오른쪽 @JeslyVarghese는 함수 자체에서 동일한 디스패치 처리기를 사용하여 재귀 호출을 수행합니다. – channi

+0

@channi : 아! 재귀 .. 좋은가요? NSTimer에 의해 달성 될 수있는 것을 위해. 지연된 함수 호출 스택이 나를 두려워합니다. 실행에 대한 제어권이 있습니까? –

답변

2
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    [self executeEveryOneMinute]; 
    return YES: 
} 

- (void)executeEveryOneMinute 
{ 
    [self myFunction] 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 

     [self executeEveryOneMinute]; 

    }); 
} 

0

이 시도 :

void runBlockInSeconds(dispatch_block_t block,int seconds) { 

    //initial block 
    block(); 

    //get current time 
    struct timespec startPopTime ; 
    gettimeofday((struct timeval*)&startPopTime, NULL); 

    //trim the time 
    startPopTime.tv_sec -= (startPopTime.tv_sec % seconds); 
    startPopTime.tv_sec +=seconds; 

    dispatch_time_t time = dispatch_walltime(&startPopTime, 0); 

    dispatch_block_t __block afterBlock = ^(void) { 
     block(); 

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * seconds), dispatch_get_main_queue(), afterBlock); 
    }; 

    dispatch_after(time, dispatch_get_main_queue(), afterBlock); 
}