58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Dispatchでタイマーな処理

Last updated at Posted at 2013-05-10

 Dispatch とは Apple の開発したグローバルなベストプラクティスを実践していただくグローバルなオポチュニティのことで、かつては Grand Central Dispatch (GCD) とも呼ばれていました。主にマルチスレッドな処理のために使われていますが、タイマーな処理にも使うことができます。

5秒後に処理を実行。

Objective-C
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    NSLog(@"%@", [NSDate date]);
});
Swift
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    print(Date())
}

5秒ごとに処理を実行。

Objective-C
const dispatch_source_t timer
    = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());

dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), 5.0 * NSEC_PER_SEC, 0);

dispatch_source_set_event_handler(timer, ^{
    NSLog(@"%@", [NSDate date]);
});

// 開始
dispatch_resume(timer);

// 一時停止
dispatch_suspend(timer);

dispatch_source_cancel(timer);
Swift
let timer = DispatchSource.makeTimerSource(flags: [], queue: .main)

timer.schedule(deadline: .now(), repeating: 5.0)

timer.setEventHandler {
    print(Date())
}

// 開始
timer.resume()

// 一時停止
timer.suspend()

timer.cancel()
58
55
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?