@@ -24,7 +24,7 @@ class ManualDispatchQueue : DispatchQueue {
2424
2525 // Filter all work items that are due to be fired and have not been
2626 // cancelled. Return early if there are no items to fire
27- val pastDueWorkItems = workItems.filter { it.deadline <= this . tickTime && ! it.isCancelled }
27+ val pastDueWorkItems = workItems.filter { it.isPastDue( tickTime) && ! it.isCancelled }
2828
2929 // if no items are due, then return early
3030 if (pastDueWorkItems.isEmpty()) return
@@ -33,10 +33,9 @@ class ManualDispatchQueue : DispatchQueue {
3333 pastDueWorkItems.forEach { it.perform() }
3434
3535 // Remove all work items that are past due or canceled
36- workItems.removeAll { it.deadline <= this . tickTime || it.isCancelled }
36+ workItems.removeAll { it.isPastDue( tickTime) || it.isCancelled }
3737 }
3838
39-
4039 override fun queue (delay : Long , unit : TimeUnit , runnable : () -> Unit ): DispatchWorkItem {
4140 // Converts the given unit and delay to the unit used by this class
4241 val delayInMs = tickTimeUnit.convert(delay, unit)
@@ -47,23 +46,56 @@ class ManualDispatchQueue : DispatchQueue {
4746
4847 return workItem
4948 }
49+
50+ override fun queueAtFixedRate (
51+ delay : Long ,
52+ period : Long ,
53+ unit : TimeUnit ,
54+ runnable : () -> Unit
55+ ): DispatchWorkItem {
56+
57+ val delayInMs = tickTimeUnit.convert(delay, unit)
58+ val periodInMs = tickTimeUnit.convert(period, unit)
59+ val deadline = tickTime + delayInMs
60+
61+ val workItem = ManualDispatchWorkItem (runnable, deadline, periodInMs)
62+ workItems.add(workItem)
63+
64+ return workItem
65+ }
5066}
5167
5268// ------------------------------------------------------------------------------
5369// Work Item
5470// ------------------------------------------------------------------------------
5571class ManualDispatchWorkItem (
5672 private val runnable : () -> Unit ,
57- val deadline : Long
73+ private var deadline : Long ,
74+ private val period : Long = 0
5875) : DispatchWorkItem {
5976
60- override var isCancelled : Boolean = false
77+ private var performCount = 0
6178
62- override fun cancel () { this .isCancelled = true }
79+
80+ // Test
81+ fun isPastDue (tickTime : Long ): Boolean {
82+ return this .deadline <= tickTime
83+ }
6384
6485 fun perform () {
6586 if (isCancelled) return
6687 runnable.invoke()
88+ performCount + = 1
89+
90+ // If the task is repeatable, then schedule the next deadline after the given period
91+ deadline + = (performCount * period)
92+ }
93+
94+ // DispatchWorkItem
95+ override var isCancelled: Boolean = false
96+
97+ override fun cancel () {
98+ this .isCancelled = true
6799 }
68100}
69101
0 commit comments