Skip to content

Commit

Permalink
Allow job to be deallocated immediately when cancelling the operation
Browse files Browse the repository at this point in the history
  • Loading branch information
lucas34 committed Nov 6, 2017
1 parent 4224fad commit ea05ec7
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 13 deletions.
7 changes: 6 additions & 1 deletion Sources/SwiftQueue/Constrains+Delay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ internal class DelayConstraint: JobConstraint {
func run(operation: SwiftQueueJob) -> Bool {
if let delay = operation.delay {
if Date().timeIntervalSince(operation.createTime) < delay {
runInBackgroundAfter(delay, callback: operation.run)
runInBackgroundAfter(delay, callback: { [weak operation = operation] in
// If the operation in already deInit, it may have been canceled
// It's safe to ignore the nil check
// This is mostly to prevent job retention when cancelling operation with delay
operation?.run()
})
return false
}
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/SwiftQueue/SwiftQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ internal final class SwiftQueue: OperationQueue {
if job.isPersisted, let sp = persister, let data = job.toJSONString() {
sp.put(queueName: queueName, taskId: job.uuid, data: data)
}
job.completionBlock = { [unowned self] in
self.completed(job)
job.completionBlock = { [weak self] in
self?.completed(job)
}
super.addOperation(ope)
}
Expand Down
27 changes: 17 additions & 10 deletions Sources/SwiftQueue/SwiftQueueJob.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,30 +153,37 @@ internal final class SwiftQueueJob: Operation, JobResult {
case .cancel:
cancel()
case .retry(let after):
retries -= 1
if after > 0 {
runInBackgroundAfter(after, callback: self.run)
runInBackgroundAfter(after) { [weak self] in
self?.retries -= 1
self?.run()
}
} else {
retries -= 1
self.run()
}
case .exponential(let initial):
let decimal: NSDecimalNumber = NSDecimalNumber(decimal: Decimal(initial) * pow(2, max(0, runCount - 1)))
runInBackgroundAfter(TimeInterval(decimal)) { [unowned self] in
self.retries -= 1
self.run()
runInBackgroundAfter(TimeInterval(decimal)) { [weak self] in
self?.retries -= 1
self?.run()
}
}
} else {
lastError = nil
runCount += 1
if maxRun >= 0 && runCount >= maxRun {
onTerminate()
} else {
if runCount + 1 < maxRun {
// Should run again
if interval > 0 {
runInBackgroundAfter(interval, callback: self.run)
runInBackgroundAfter(interval, callback: { [weak self] in
self?.runCount += 1
self?.run()
})
} else {
runCount += 1
self.run()
}
} else {
onTerminate()
}
}
}
Expand Down

0 comments on commit ea05ec7

Please sign in to comment.