SwiftQueue Documentation

repository·master·Indexed 19 days ago

https://github.com/lucas34/swiftqueue

A job scheduler for Apple platforms (iOS, macOS, tvOS, watchOS) that allows developers to run tasks with specific run and retry constraints. Built using Operation and OperationQueue, it supports execution timing, connectivity requirements, device state constraints, and periodic tasks.

Tokens
1.3K
Snippets
5
Records
6
Agent score
15%

What's inside SwiftQueue

  1. Supported Job Constraints

    master

    SwiftQueue allows you to apply various constraints to jobs to control when they run and how they behave:

    • Execution Timing: Delay, Deadline, Timeout.
    • Connectivity: Internet (e.g., requiring cellular data).
    • Device State: Charging.
    • Queue Logic: Single instance in queue (prevents duplicate jobs of the same type).
    • Retry Logic: Retry with Max count and exponential backoff.
    • Periodic Tasks: Periodic with Max run and interval delay.
    • Execution Context: Experimental Foreground or Background execution.
  2. Install SwiftQueue

    master

    You can install SwiftQueue using Swift Package Manager, Carthage, or CocoaPods.

    #### SwiftPackageManager (SPM)
    ```swift
    .package(url: "https://github.com/lucas34/SwiftQueue.git", .upToNextMajor(from: "4.0.0"))

    Carthage

    github "lucas34/SwiftQueue"

    CocoaPods

    platform :ios, '8.0'
    use_frameworks!
    pod 'SwiftQueue'
  3. Initialize and use SwiftQueueManager

    master

    To manage your queue, use SwiftQueueManagerBuilder with a JobCreator.

    Important: You must maintain a strong reference to the SwiftQueueManager instance. If you want to cancel jobs, you must use the same instance that was used to schedule them.

    let manager = SwiftQueueManagerBuilder(creator: TweetJobCreator()).build()
  4. Schedule a job with constraints using JobBuilder

    master

    Use JobBuilder to define a job's type, provide parameters, apply constraints, and schedule it with a SwiftQueueManager instance.

    JobBuilder(type: SendTweetJob.type)
            .internet(atLeast: .cellular)
            .with(params: ["content": "Hello world"])
            .schedule(manager: manager)
  5. Create a custom job by extending Job

    master

    To define a task, create a class that conforms to the Job protocol. You must implement the following:

    1. static let type: String: A unique identifier for the job type.
    2. required init(params: [String: Any]): An initializer to receive parameters passed via JobBuilder.with(params:).
    3. onRun(callback: JobResult): The core logic of the job. Use the callback to signal .success or .fail(error).
    4. onRetry(error: Error) -> RetryConstraint: Logic to determine if a failed job should be retried or cancelled. Returns a RetryConstraint.
    5. onRemove(result: JobCompletion): A callback triggered when the job is finished (either successfully or after all retries fail).
    class SendTweetJob: Job {
        static let type = "SendTweetJob"
        private let tweet: [String: Any]
    
        required init(params: [String: Any]) {
            self.tweet = params
        }
    
        func onRun(callback: JobResult) {
            let api = Api()
            api.sendTweet(data: tweet).execute(onSuccess: {
                callback.done(.success)
            }, onError: {
                callback.done(.fail(error))
            })
        }
    
        func onRetry(error: Error) -> RetryConstraint {
            return error is ApiError ? RetryConstraint.cancel : RetryConstraint.retry(delay: 0)
        }
    
        func onRemove(result: JobCompletion) {
            switch result {
            case .success: break
            case .fail(let error): break
            }
        }
    }
  6. Implement a JobCreator

    master

    A JobCreator is responsible for instantiating the correct Job class based on a string type. You must implement the create(type:params:) method. This is used by the SwiftQueueManagerBuilder to know how to rebuild jobs from persistent storage or when scheduling new ones.

    class TweetJobCreator: JobCreator {
        func create(type: String, params: [String: Any]?) -> Job {
            if type == SendTweetJob.type  {
                return SendTweetJob(params: params)
            } else {
                fatalError("No Job !")
            }
        }
    }