Skip to content

Instantly share code, notes, and snippets.

@KunalKumarSwift
Created June 11, 2024 19:05
Show Gist options
  • Save KunalKumarSwift/84e60d0a6a9184e536e9e1959172f326 to your computer and use it in GitHub Desktop.
Save KunalKumarSwift/84e60d0a6a9184e536e9e1959172f326 to your computer and use it in GitHub Desktop.
TaskQueue Swift
import Foundation
struct Task {
let priority: Int
let completion: () -> Bool // Returns a Bool indicating success or failure
let onFailure: () -> Void
let proceedOnFailure: Bool
}
class TaskQueue {
private var tasks: [Task] = []
private let queue = DispatchQueue(label: "taskQueue")
private var isExecutingTask = false
private var isStarted = false
func addTask(_ task: Task) {
queue.async {
self.tasks.append(task)
self.tasks.sort { $0.priority > $1.priority } // Higher priority first
}
}
func startExecution() {
queue.async {
guard !self.isStarted else { return }
self.isStarted = true
self.executeNextTask()
}
}
private func executeNextTask() {
guard !isExecutingTask, !tasks.isEmpty else { return }
isExecutingTask = true
let nextTask = tasks.removeFirst()
// Execute task and determine success or failure
let success = nextTask.completion()
if success {
self.queue.async {
self.isExecutingTask = false
self.executeNextTask()
}
} else {
nextTask.onFailure()
self.queue.async {
self.isExecutingTask = false
if nextTask.proceedOnFailure {
self.executeNextTask()
} else {
self.isStarted = false
}
}
}
}
}
// Example Usage
let taskQueue = TaskQueue()
taskQueue.addTask(Task(priority: 1,
completion: {
print("Task with priority 1 executed")
return true // Indicate success
},
onFailure: {
print("Task with priority 1 failed")
},
proceedOnFailure: true))
taskQueue.addTask(Task(priority: 3,
completion: {
print("Task with priority 3 executed")
return false // Indicate failure
},
onFailure: {
print("Task with priority 3 failed")
},
proceedOnFailure: true))
taskQueue.addTask(Task(priority: 2,
completion: {
print("Task with priority 2 executed")
return true // Indicate success
},
onFailure: {
print("Task with priority 2 failed")
},
proceedOnFailure: false))
taskQueue.startExecution()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment