Skip to content

Instantly share code, notes, and snippets.

@jrsonline
Created June 15, 2019 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrsonline/ccd2338f6e39a2f0c7e7640063a0182c to your computer and use it in GitHub Desktop.
Save jrsonline/ccd2338f6e39a2f0c7e7640063a0182c to your computer and use it in GitHub Desktop.
Simple FutureScheduler for Apple's combine, like ImmediateScheduler
struct FutureScheduler : Scheduler {
var now: DispatchTime { get { return DispatchTime.now() }}
var minimumTolerance: Int64 = 1
func schedule(after date: DispatchTime, tolerance: Int64, options: Never?, _ action: @escaping () -> Void) {
_ = self.schedule(after: date, interval: .seconds(0), tolerance: tolerance, options: nil, action)
}
func schedule(after date: DispatchTime, interval: Int64, tolerance: Int64, options: Never?, _ action: @escaping () -> Void) -> Cancellable {
FutureScheduledAction( action, at: date)
}
func schedule(options: Never?, _ action: @escaping () -> Void) {
_ = self.schedule(after: now, interval: .seconds(0), tolerance: minimumTolerance, options: nil, action)
}
}
extension DispatchTime : Strideable {
public typealias Stride = Int64
public func distance(to other: DispatchTime) -> Int64 {
Int64(other.rawValue) - Int64(self.rawValue)
}
public func advanced(by n: Int64) -> DispatchTime {
self + Double(n) // warning of overflows here!
}
}
extension Int64 : SchedulerTimeIntervalConvertible {
public static func seconds(_ s: Int) -> Int64 {
return Int64(s * 1_000_000_000)
}
public static func seconds(_ s: Double) -> Int64 {
return Int64(s * 1_000_000_000)
}
public static func milliseconds(_ ms: Int) -> Int64 {
return Int64(ms * 1_000_000)
}
public static func microseconds(_ us: Int) -> Int64 {
Int64(us * 1_000)
}
public static func nanoseconds(_ ns: Int) -> Int64 {
return Int64(ns)
}
}
struct FutureScheduledAction : Cancellable {
var workItem : DispatchWorkItem
init(_ action: @escaping () -> Void, at: DispatchTime) {
workItem = DispatchWorkItem {
action()
}
DispatchQueue.global().asyncAfter(deadline: at, execute: workItem)
}
func cancel() {
workItem.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment