Last active
January 30, 2020 02:22
-
-
Save zentrope/fb9e1f8564bf148344a34ac30a17615a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Cocoa | |
class ActivityManager { | |
var activityUpdate: NSBackgroundActivityScheduler? | |
var serialize = DispatchQueue(label: "sync", qos: .background) | |
func backgroundActivitiesSetup() { | |
print("Setting up activity runner.") | |
activityUpdate = NSBackgroundActivityScheduler(identifier: "…") | |
activityUpdate?.interval = 15 // 1 * 60 // every 1 minute | |
activityUpdate?.repeats = true | |
activityUpdate?.schedule { completion in | |
self.serialize.async { | |
self.updateNewItems(completion) | |
} | |
} | |
} | |
func getNewItemsNow() { | |
// The serialize queue should make sure no update new items requests overlap. | |
serialize.async { | |
self.updateNewItems() | |
} | |
} | |
func updateNewItems(_ completion: NSBackgroundActivityScheduler.CompletionHandler? = nil) { | |
defer { completion?(.finished) } | |
print("\(Date()) Updating new items.") | |
let numWorkers = 10 | |
let batchCount = 160 | |
var (items, totalItems) = (Array(0..<10), 100) // stub | |
while totalItems > 0 { | |
let lock = DispatchSemaphore(value: numWorkers) | |
var startTime = Date() | |
print("\(startTime) Update [\(items.count) of \(totalItems) items] started.") | |
DispatchQueue.concurrentPerform(iterations: numWorkers) { index in | |
defer { lock.signal() } | |
let start = index * items.count / numWorkers | |
let end = (index + 1) * items.count / numWorkers | |
for _ in start ..< end { | |
let random = Int.random(in: 0 ..< items.count) | |
// work here | |
print("\(Date()) Update completed for \(items[random]).") | |
} | |
} | |
lock.wait() | |
let totalTime = DateInterval(start: startTime, end: Date()).duration | |
print("\(Date()) Update [\(items.count) of \(totalItems) items] completed in \(totalTime) seconds.") | |
(items, totalItems) = ([], 0) // stub | |
} | |
} | |
} | |
let a = ActivityManager() | |
DispatchQueue.global().asyncAfter(deadline: .now() + 15) { | |
print("RUNNING AD HOC REQUEST") | |
a.getNewItemsNow() | |
} | |
a.backgroundActivitiesSetup() | |
print("Waiting.") | |
RunLoop.current.run() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment