Last active
January 29, 2020 02:14
-
-
Save zentrope/64b76e87d1b0bd5423ba33d5cab4672a 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
var activityUpdate: NSBackgroundActivityScheduler? | |
func backgroundActivitiesSetup() { | |
activityUpdate = NSBackgroundActivityScheduler(identifier: "…") | |
activityUpdate?.interval = 1 * 60 // every 1 minute | |
activityUpdate?.repeats = true | |
activityUpdate?.schedule { completion in | |
updateNewItems(completion) | |
} | |
} | |
func updateNewItems(_ completion: NSBackgroundActivityScheduler.CompletionHandler) { | |
let numWorkers = 10 | |
let batchCount = 160 | |
var (items, totalItems) = … | |
while totalItems > 0 { | |
let lock = DispatchSemaphore(value: numWorkers) | |
var startTime = Date() | |
print("\(startTime.localDate()) 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().localDate()) Update completed for \(items[random].name).") | |
} | |
} | |
lock.wait() | |
let totalTime = Date().offsetFrom(date: startTime) | |
print("\(Date().localDate()) Update [\(items.count) of \(totalItems) items] completed in \(totalTime).") | |
(items, totalItems) = // retrieve more items | |
} | |
completion(.finished) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment