Block for excuting task after fixed interval give NSTimer a miss

Hi,

If ever you feel the need to repeat a task after say 5 seconds and you feel nastimer is too clumsy to use then you can use…

 

void runBlockEveryMinute(int *breakCondition, dispatch_block_t block) {
if(*breakCondition==0)
{
return;
}
block();
// initial block call // get the current time
struct timespec startPopTime;
gettimeofday((struct timeval *) &startPopTime, NULL); // trim the time
startPopTime.tv_sec -= (startPopTime.tv_sec % 5); startPopTime.tv_sec += 5;//5 for 5 second make it 60 for one min
dispatch_time_t time = dispatch_walltime(&startPopTime, 0);
dispatch_block_t __block afterBlock = ^(void) {
if(*breakCondition==0)
return ;
block();
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 5), dispatch_get_main_queue(), afterBlock);
};
dispatch_after(time, dispatch_get_main_queue(), afterBlock); // start the 'timer' going notice the recursive call
}

This is a static C style function call it where you want it

runBlockEveryMinute(&flagBreak, ^{
// this will get called every 5 sec

});

when ever you need to stop it just set the value of int flagBreak to 1or any non zero value;
hope this helps some one.

A pat on the back !!

Leave a Reply

Your email address will not be published. Required fields are marked *