Skip to content

Instantly share code, notes, and snippets.

@zentrope
Last active January 29, 2020 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zentrope/64b76e87d1b0bd5423ba33d5cab4672a to your computer and use it in GitHub Desktop.
Save zentrope/64b76e87d1b0bd5423ba33d5cab4672a to your computer and use it in GitHub Desktop.
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