轻松安排具有约束的任务。
SwiftQueue
是一个 iOS 任务调度器,其灵感来自流行的 Android 库,如 android-priority-jobqueue 或 android-job。 它允许您运行带有运行和重试约束的任务。
该库将依赖于 Operation
和 OperationQueue
以确保所有任务按顺序运行。 不要忘记查看我们的WIKI。
任务约束
要使用 Apple 的 Swift 包管理器进行集成,请将以下内容作为依赖项添加到您的 Package.swift
.package(url: "https://github.com/lucas34/SwiftQueue.git", .upToNextMajor(from: "4.0.0"))
SwiftQueue
与 carthage
兼容。 将以下条目添加到您的 Cartfile
github "lucas34/SwiftQueue"
然后运行 carthage update
。
您可以使用 CocoaPods 安装 SwiftQueue
,方法是将其添加到您的 Podfile
platform :ios, '8.0'
use_frameworks!
pod 'SwiftQueue'
在您的应用程序中,只需导入该库
import SwiftQueue
此示例将简单地包装一个 api 调用。 通过使用 onRun
、onRetry
和 onRemove
回调扩展 Job
来创建您的自定义任务。
// A job to send a tweet
class SendTweetJob: Job {
// Type to know which Job to return in job creator
static let type = "SendTweetJob"
// Param
private let tweet: [String: Any]
required init(params: [String: Any]) {
// Receive params from JobBuilder.with()
self.tweet = params
}
func onRun(callback: JobResult) {
let api = Api()
api.sendTweet(data: tweet).execute(onSuccess: {
callback.done(.success)
}, onError: { error in
callback.done(.fail(error))
})
}
func onRetry(error: Error) -> RetryConstraint {
// Check if error is non fatal
return error is ApiError ? RetryConstraint.cancel : RetryConstraint.retry(delay: 0) // immediate retry
}
func onRemove(result: JobCompletion) {
// This job will never run anymore
switch result {
case .success:
// Job success
break
case .fail(let error):
// Job fail
break
}
}
}
创建您的 SwiftQueueManager
并**保留引用**。 如果您想取消任务,必须使用相同的实例完成。
let manager = SwiftQueueManagerBuilder(creator: TweetJobCreator()).build()
安排您的任务并指定约束。
JobBuilder(type: SendTweetJob.type)
// Requires internet to run
.internet(atLeast: .cellular)
// params of my job
.with(params: ["content": "Hello world"])
// Add to queue manager
.schedule(manager: manager)
将您的 job
类型与实际实例绑定。
class TweetJobCreator: JobCreator {
// Base on type, return the actual job implementation
func create(type: String, params: [String: Any]?) -> Job {
// check for job and params type
if type == SendTweetJob.type {
return SendTweetJob(params: params)
} else {
// Nothing match
// You can use `fatalError` or create an empty job to report this issue.
fatalError("No Job !")
}
}
}
我们非常感谢您对 SwiftQueue 的贡献,请查看 LICENSE
文件以获取更多信息。
根据 MIT 许可证分发。 有关更多信息,请参见 LICENSE
。