Swift

var timer : DispatchSourceTimer? Func startTimer() {var timeCount = 10 // create a time source in the global thread if timer == nil {timer = 1 DispatchSource. MakeTimerSource (queue: DispatchQueue. Global ())} / / set the time source is once per cycle, immediately start the timer? .schedule(deadline:.now(), repeating:.seconds(1)) // Set the trigger event timer for the time source? .setEventHandler(handler: Print (" Timer :", TimeCount) // TimeCount = TimeCount-1 // TimeCount <= 0 { Self. StOptimer () DispatchQueue.main.async {// The UI operation is placed on the main thread}}}) // Start time source timer? .resume()} // stop the timer func stOptimer () {print(" timer is over ") timer? .cancel() timer = nil }

Objective-C

@interface ViewController () { dispatch_source_t _timer; } @end -(void)startTimer{ __block NSInteger timeCount = 10; dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0)); dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); Dispatch_source_set_event_handler (timer, ^{NSLog(@" timer :%li",(long)timeCount); timeCount --; if (timeCount <= 0) { [self stopTimer]; dispatch_async(dispatch_get_main_queue(), ^{ }); }}); dispatch_resume(timer); _timer = timer; } -(void)stopTimer{ dispatch_source_cancel(_timer); _timer = nil; }

Two things to note:

  • According to this method to stop the timer, can be reused, usesuspendThe stop timer cannot be reused
  • timerTo be set as a global object. Otherwise, after the code is finished executingtimerAnd he was released; And convenient to operate in other places, such as pause, cancel, empty.