SHARE
TWEET

Untitled

a guest Jun 26th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct FutureScheduler : Scheduler {
  2.     var now: DispatchTime { get { return DispatchTime.now() }}
  3.     var minimumTolerance: Int64 = 1
  4.    
  5.     func schedule(after date: DispatchTime, tolerance: Int64, options: Never?, _ action: @escaping () -> Void) {
  6.         _ = self.schedule(after: date, interval: .seconds(0), tolerance: tolerance, options: nil, action)
  7.     }
  8.    
  9.     func schedule(after date: DispatchTime, interval: Int64, tolerance: Int64, options: Never?, _ action: @escaping () -> Void) -> Cancellable {
  10.         FutureScheduledAction( action, at: date)
  11.     }
  12.    
  13.     func schedule(options: Never?, _ action: @escaping () -> Void) {
  14.         _ = self.schedule(after: now, interval: .seconds(0), tolerance: minimumTolerance, options: nil, action)
  15.     }
  16. }
  17.  
  18. extension DispatchTime : Strideable {
  19.     public typealias Stride = Int64
  20.    
  21.     public func distance(to other: DispatchTime) -> Int64 {
  22.         Int64(other.rawValue) - Int64(self.rawValue)
  23.     }
  24.    
  25.     public func advanced(by n: Int64) -> DispatchTime {
  26.         self + Double(n)   // warning of overflows here!
  27.     }
  28.    
  29. }
  30.  
  31. extension Int64 : SchedulerTimeIntervalConvertible {
  32.     public static func seconds(_ s: Int) -> Int64 {
  33.         return Int64(s * 1_000_000_000)
  34.     }
  35.    
  36.     public static func seconds(_ s: Double) -> Int64 {
  37.         return Int64(s * 1_000_000_000)
  38.     }
  39.    
  40.     public static func milliseconds(_ ms: Int) -> Int64 {
  41.         return Int64(ms * 1_000_000)
  42.     }
  43.    
  44.     public static func microseconds(_ us: Int) -> Int64 {
  45.         Int64(us * 1_000)
  46.     }
  47.    
  48.     public static func nanoseconds(_ ns: Int) -> Int64 {
  49.         return Int64(ns)
  50.     }
  51. }
  52.  
  53. struct FutureScheduledAction : Cancellable {
  54.     var workItem : DispatchWorkItem
  55.    
  56.     init(_ action: @escaping () -> Void, at: DispatchTime) {
  57.         workItem = DispatchWorkItem {
  58.             action()
  59.         }
  60.         DispatchQueue.global().asyncAfter(deadline: at, execute: workItem)
  61.     }
  62.  
  63.     func cancel() {
  64.         workItem.cancel()
  65.     }
  66.    
  67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top