|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Released under the MIT License. |
| 4 | +# Copyright, 2025, by Samuel Williams. |
| 5 | + |
| 6 | +module Async |
| 7 | + # Represents a flexible timeout that can be rescheduled or extended. |
| 8 | + # @public Since *Async v2.24*. |
| 9 | + class Timeout |
| 10 | + # Initialize a new timeout. |
| 11 | + def initialize(timers, handle, duration = nil) |
| 12 | + @timers = timers |
| 13 | + @handle = handle |
| 14 | + @duration = duration || (handle.time - timers.now) |
| 15 | + end |
| 16 | + |
| 17 | + # @attribute [Numeric] The duration of the timeout. |
| 18 | + attr :duration |
| 19 | + |
| 20 | + # Update the duration of the timeout, rescheduling it if necessary. |
| 21 | + # |
| 22 | + # The duration is relative to the time the timeout was created. |
| 23 | + # |
| 24 | + # @parameter value [Numeric] The new duration to assign to the timeout. |
| 25 | + def duration=(value) |
| 26 | + delta = value - @duration |
| 27 | + self.reschedule(time + delta, value) |
| 28 | + end |
| 29 | + |
| 30 | + # Adjust the timeout by the specified duration, rescheduling it if necessary. |
| 31 | + # |
| 32 | + # @parameter duration [Numeric] The duration to adjust the timeout by. |
| 33 | + # @returns [Numeric] The new time at which the timeout will occur. |
| 34 | + def adjust(duration) |
| 35 | + self.reschedule(time + duration, @duration + duration) |
| 36 | + end |
| 37 | + |
| 38 | + # @returns [Numeric] The time at which the timeout will occur. |
| 39 | + def time |
| 40 | + @handle.time |
| 41 | + end |
| 42 | + |
| 43 | + # Assign a new time to the timeout, rescheduling it if necessary. |
| 44 | + # |
| 45 | + # @parameter value [Numeric] The new time to assign to the timeout. |
| 46 | + # @returns [Numeric] The new time at which the timeout will occur. |
| 47 | + def time=(value) |
| 48 | + self.reschedule(value) |
| 49 | + end |
| 50 | + |
| 51 | + # Cancel the timeout. |
| 52 | + def cancel! |
| 53 | + @handle.cancel! |
| 54 | + end |
| 55 | + |
| 56 | + # @returns [Boolean] Whether the timeout has been cancelled. |
| 57 | + def cancelled? |
| 58 | + @handle.cancelled? |
| 59 | + end |
| 60 | + |
| 61 | + # Reschedule the timeout to occur at the specified time. |
| 62 | + # |
| 63 | + # @parameter time [Numeric] The new time to schedule the timeout for. |
| 64 | + # @parameter duration [Numeric | Nil] The new duration to assign to the timeout. |
| 65 | + # @returns [Numeric] The new time at which the timeout will occur. |
| 66 | + private def reschedule(time, duration = nil) |
| 67 | + if block = @handle&.block |
| 68 | + @handle.cancel! |
| 69 | + |
| 70 | + @duration = duration || (time - @timers.now) |
| 71 | + @handle = @timers.schedule(time, block) |
| 72 | + |
| 73 | + return time |
| 74 | + else |
| 75 | + raise RuntimeError, "Cannot reschedule a cancelled timeout!" |
| 76 | + end |
| 77 | + end |
| 78 | + end |
| 79 | +end |
0 commit comments