Skip to content

Instantly share code, notes, and snippets.

@zentrope
Last active January 29, 2020 01:16
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/4100ff3b4be832c0c3ed75078a4017a5 to your computer and use it in GitHub Desktop.
Save zentrope/4100ff3b4be832c0c3ed75078a4017a5 to your computer and use it in GitHub Desktop.
var activity: NSBackgroundActivityScheduler?
func runActivity() {
activity = NSBackgroundActivityScheduler(identifier: "lkasjdlaksjdaslkjd")
activity?.repeats = true
activity?.interval = 15
activity?.schedule { completion in
// This doesn't make sense: defer should be periodically checked in
// the middle of a long job.
if let activity = self.activity, activity.shouldDefer {
completion(.deferred)
return
}
// Running a bunch of concurrent stuff is fine, but hard to manage
// if you're worried about needing to defer.
let numWorkers = 10
let lock = DispatchSemaphore(value: numWorkers)
let date = Date()
DispatchQueue.concurrentPerform(iterations: numWorkers) { (index) in
defer { lock.signal() }
print("activity [\(date)] - \(index)")
}
lock.wait()
print("done")
completion(.finished)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment