Last active
February 19, 2022 08:23
-
-
Save maximkrouk/07213e57403d66b7800e5f18df1dbf8f to your computer and use it in GitHub Desktop.
Scheduled task wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Bundle { | |
var id: String { bundleIdentifier ?? "" } | |
} | |
@propertyWrapper | |
public class Scheduled { | |
private static let defaultQueue = DispatchQueue( | |
label: Bundle.main.id.appending(".queues.scheduled"), | |
qos: .utility, | |
autoreleaseFrequency: .workItem | |
) | |
private let lock = NSLock() | |
private(set) var isSuspended = false | |
public let interval: TimeInterval | |
public let delay: TimeInterval | |
public let queue: DispatchQueue | |
public var action: () -> Void | |
public init( | |
interval: TimeInterval, | |
delay: TimeInterval = 0, | |
action wrappedValue: @escaping () -> Void = {}) | |
{ | |
self.interval = interval | |
self.delay = delay | |
self.queue = Scheduled.defaultQueue | |
self.action = wrappedValue | |
} | |
public init( | |
interval: TimeInterval, | |
delay: TimeInterval = 0, | |
queue: DispatchQueue, | |
action wrappedValue: @escaping () -> Void = {}) | |
{ | |
self.interval = interval | |
self.delay = delay | |
self.queue = queue | |
self.action = wrappedValue | |
} | |
public var wrappedValue: () -> Void { | |
get { action } | |
set { | |
action = newValue | |
resume() | |
} | |
} | |
public func suspend() { | |
lock.store(true, in: &isSuspended) | |
} | |
public func resume() { | |
lock.store(false, in: &isSuspended) | |
queue.asyncAfter(deadline: .now() + delay) { | |
self.runLoop() | |
} | |
} | |
private func runLoop(_ active: Bool = true) { | |
guard active else { return } | |
action() | |
let shouldStopExecution = isSuspended | |
queue.asyncAfter(deadline: .now() + interval) { [weak self] in | |
self?.runLoop(!shouldStopExecution) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
UsageExample
Also you can use
Back to index