GCD: How to change the timer interval

In any case, this may sound like a newbie question, I'm very new to GCD

I have a code:

int interval = 2; int leeway = 0; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); if (timer) { dispatch_source_set_timer(timer, dispatch_walltime(DISPATCH_TIME_NOW, NSEC_PER_SEC * interval), interval * NSEC_PER_SEC, leeway); dispatch_source_set_event_handler(timer, ^{ [self someMethod]; }); dispatch_resume(timer); } 

Where someMethod:

 - (void)someMethod { NSLog(@"Thread 1"); } 

How to change the timer interval property in someMethod?

+6
source share
2 answers

Got a response on my own by calling dispatch_source_set_timer with a new interval value

+9
source

@deimus I also ran into the problem of changing the sending interval. Please refer below code

 dispatch_source_t aTimer; void someMethod (){ printf("In timer\n"); dispatch_source_set_timer(aTimer, dispatch_walltime(NULL, 0), 10ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC); } dispatch_source_t CreateDispatchTimer(uint64_t interval, uint64_t leeway, dispatch_queue_t queue) { dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); if (timer) { dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway); dispatch_source_set_event_handler(timer, ^{ someMethod(); }); dispatch_resume(timer); } return timer; } void MyCreateTimer() { aTimer = CreateDispatchTimer(1ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC, dispatch_get_main_queue()); [aTimer retain]; // Store it somewhere for later use. if (aTimer) { NSLog(@"Created Timer"); } } 

According to your answer, the timer interval should change when dispatch_source_set_timer () is called with a new time interval, in someMethod (). But this does not work as expected! The timer fires in an explosion. It looks like the timer interval is set to zero. I am new to iOS programming. Please let me know if I am doing wrong.

0
source

Source: https://habr.com/ru/post/918274/


All Articles