Skip to main content

CallbackTimer

Struct CallbackTimer 

Source
pub struct CallbackTimer { /* private fields */ }
Expand description

A reusable, local one-shot callback timer.

Each construction or reset arms one invocation of the retained callback. The callback may capture Rc state; this handle is neither Send nor Sync and cannot be cloned. Keep the handle alive until the callback should run. Dropping it cancels pending delivery, including an expired callback that has not started, and releases its captures. An active invocation retains its captures until it finishes.

Expiration and cancellation retain the callback for reuse. The callback implements Fn, so use interior mutability for state that changes between invocations.

Callbacks run outside wheel access and may create, reset, cancel or drop timers, including themselves. They must be short, synchronous and non-blocking. Callbacks due on the same tick have no guaranteed order.

Callback panics propagate through the runtime. They may stop the shared driver and disarm other timers; remaining callbacks need not be delivered. Runtime shutdown suppresses pending delivery. A surviving handle retains its callback and can be explicitly reset in a new runtime on the same thread. Starting a new runtime does not automatically rearm the handle.

§Examples

Retain local state across invocations, cancel an arm, then reuse the timer:

use std::{cell::Cell, rc::Rc};
use ntex::time::{CallbackTimer, Millis, sleep};

#[ntex::main]
async fn main() {
    let calls = Rc::new(Cell::new(0));
    let count = calls.clone();
    let timer = CallbackTimer::new(Millis::ZERO, move || {
        count.set(count.get() + 1);
    });
    assert_eq!(calls.get(), 0); // Zero duration never invokes inline.
    sleep(Millis(50)).await;
    assert!(timer.is_elapsed());
    assert_eq!(calls.get(), 1);

    timer.reset(Millis(1_000));
    timer.cancel();
    assert!(timer.is_elapsed());

    timer.reset(Millis::ZERO);
    sleep(Millis(50)).await;
    assert_eq!(calls.get(), 2);
}

Implementations§

Source§

impl CallbackTimer

Source

pub fn new(duration: Millis, callback: impl Fn() + 'static) -> Self

Arms a callback after duration, using the wheel’s rounding and limits.

The base granularity is approximately 16 ms; longer delays use coarser rounding, and delays beyond the wheel’s capacity (about 24 days) are clamped. Callback delivery may be delayed further while the runtime is busy.

A zero duration waits for a subsequent timer tick, as with crate::time::Sleep; the callback is never invoked inline.

Source

pub fn reset(&self, duration: Millis)

Arms another invocation, invalidating any previous pending delivery.

This also suppresses an expired invocation that has been queued but has not started. It can be called before or after expiration or cancellation.

A zero duration waits for a subsequent tick. Resetting from within the callback arms a new invocation, which survives completion of the old one.

Source

pub fn cancel(&self)

Disarms the timer and suppresses pending delivery, retaining the callback.

This also suppresses an expired invocation that has not started. Calling this method on an already disarmed timer is harmless.

An invocation that has already started cannot be interrupted.

Source

pub fn is_elapsed(&self) -> bool

Returns true when disarmed, including after cancellation or shutdown.

Expiration marks the timer elapsed before callback delivery. This query does not indicate whether the callback has run.

Trait Implementations§

Source§

impl Debug for CallbackTimer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for CallbackTimer

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.