Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift command line script using NSOperation.
#!/usr/bin/env xcrun swift
//
// SwiftCommandLineWithNSOperation.swift
// SwiftCommandLineWithNSOperation
//
// Created by Richard Stelling on 27/11/2015.
// Copyright © 2015 Richard Stelling. All rights reserved.
//
import Foundation
// Set up the NSOperationQueue, the higher you set maxConcurrentOperationCount
// the quicker all the operation will finish (up to 10)
var queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 5 //Deadlock if this is = 1
queue.qualityOfService = .Utility
let start = NSDate()
let outterOp = NSBlockOperation {
for i in 0..<10 {
let op = NSBlockOperation {
for j in 0..<5 {
sleep(1)
print("*", terminator: "")
fflush(__stdoutp)
}
}
queue.addOperation(op)
print("|")
sleep(2)
}
}
queue.addOperation(outterOp)
// This will block until all our operation have compleated (or been canceled)
queue.waitUntilAllOperationsAreFinished()
let end = NSDate()
let delta = end.timeIntervalSinceDate(start)
print("\n\nOperation took \(floor(delta)) wall clock seconds")
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.