Created
January 25, 2021 14:22
-
-
Save macneko-ayu/2bc88d522d448c8f7cd6a8ec6d983af6 to your computer and use it in GitHub Desktop.
OperationQueue sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
final class SampleOperation: Operation { | |
let message: String | |
init(message: String) { | |
self.message = message | |
} | |
override func main() { | |
if isCancelled { | |
return | |
} | |
sleep(10) | |
print("\(message) \(Date().timeIntervalSince1970)") | |
} | |
} | |
let sample1 = SampleOperation(message: "foo") | |
let sample2 = SampleOperation(message: "bar") | |
let sample3 = SampleOperation(message: "hoge") | |
let queue = OperationQueue() | |
// 実行数を1にする | |
queue.maxConcurrentOperationCount = 1 | |
// queueに追加すると順次実行される | |
queue.addOperation(sample1) | |
queue.addOperation(sample2) | |
if sample1.isExecuting { | |
// sample1のOperationが実行中なら、sample2をキャンセルする | |
sample2.cancel() | |
} | |
queue.addOperation(sample3) | |
/* | |
実行結果 | |
foo 1611583657.37749 | |
hoge 1611583667.378951 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment