-
Notifications
You must be signed in to change notification settings - Fork 43
Home
Lucas Nelaupe edited this page Aug 18, 2017
·
18 revisions
SwiftQueue is a library built on top of Operation and OperationQueue that allows you to specify run and retry constraints to your jobs.
SwiftQueue is available on CocoaPod repository. There is no support for Carthage yet.
pod 'SwiftQueue'
In the following example we will create step by step tweet sending that use SwiftQueue to keep tweets ordering.
Each queue you will create will run independently. SwiftQueue only requires 1 argument, an array of creator. See Job Creation section. You can also specify an identifier to your queue by using the convenience initialiser
let tweetQueue = SwiftQueue(creators: [TweetJobCreator()])
JobBuilder(taskID: taskID, jobType: SendTweetJob.type)
// Sending tweet will require internet. At least cellular.
// Will also be executed if connected to wifi.
.internet(atLeast: .cellular)
// Content of your tweet. Can be a class, struct or anything
.with(params: "Hello TweetWorld")
// Retry maximum 5 times if the job fail before removing from the queue
.retry(max: 5)
// Insert to queue
.schedule(queue: queue)
class SendTweetJob: Job {
public static let type = "SendTweetJob"
private let tweetMessage: String
// Argument specified in JobBuilder.with()
required init(message: String) {
self.tweetMessage = message
}
func onRunJob(callback: JobResult) throws {
// Actual sending is happening here
API.sendTweet(type: "TEXT", content: tweetMessage)
.onSucess {
// Notify job done without error
callback.onDone(error: nil)
}.onFail { error in
// Job failed.
callback.onDone(error: error)
}
}
func onError(error: Error) -> RetryConstraint {
// When a job failed. Since we put retry(max: 5).
// This callback will be called at most 5 times
// Specify if we still want to retry or not.
if error is ApiError {
// No need for retry, Server rejected the message.
// Will remove job from queue even if retry counter > 0
return RetryConstraint.cancel
} else {
// Job will run again. Retry counter will decrease
return RetryConstraint.retry
}
}
func onComplete() {
// Job is removed from queue and successfully ran
// Update your UI or your database
}
func onCancel() {
// Job is removed from queue but the job failed.
// Can be due to deadline, retry count reach limit, or RetryConstraint.cancel
// Update your UI or your database
}
}
class TweetJobCreator: JobCreator {
func create(jobType: String, params: Any?) -> Job? {
// params as specified in JobBuilder.with()
if jobType == SendTweetJob.type, let message = params as? String {
// Return our actual job.
return SendTweetJob(message: message)
} else {
// Nothing match
return nil
}
}
}