pub fn every<F>(duration: Duration, f: F) -> CmdExpand description
Creates a command that produces messages repeatedly at a regular interval.
This command will continuously send messages produced by the provided closure f
after every duration until the program exits or the timer is cancelled.
Unlike tick(), this creates a persistent timer that keeps firing.
Warning: Be careful not to call every() repeatedly for the same timer,
as this will create multiple concurrent timers that can overwhelm the
event loop. Instead, call it once and use cancel_timer() if needed.
§Arguments
duration- The duration between messagesf- A closure that takes aDurationand returns aMsg
§Returns
A command that will produce messages repeatedly at the specified interval
§Examples
use bubbletea_rs::{command, Model, Msg};
use std::time::Duration;
#[derive(Debug)]
struct ClockTickMsg;
struct MyModel {
time_elapsed: Duration,
}
impl Model for MyModel {
fn init() -> (Self, Option<command::Cmd>) {
let model = Self { time_elapsed: Duration::from_secs(0) };
// Start a timer that fires every second
let cmd = command::every(Duration::from_secs(1), |_| {
Box::new(ClockTickMsg) as Msg
});
(model, Some(cmd))
}
fn update(&mut self, msg: Msg) -> Option<command::Cmd> {
if msg.downcast_ref::<ClockTickMsg>().is_some() {
self.time_elapsed += Duration::from_secs(1);
// No need to re-arm - it keeps firing automatically
}
None
}
fn view(&self) -> String {
format!("Time elapsed: {:?}", self.time_elapsed)
}
}