Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement