From 0f3583adfdf2a13acf4a3a53ff989f05b352971a Mon Sep 17 00:00:00 2001 From: galenseilis Date: Tue, 5 Nov 2024 21:02:33 -0800 Subject: [PATCH] doc:readme:example --- desru/README.md | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/desru/README.md b/desru/README.md index 96fb901..6709681 100644 --- a/desru/README.md +++ b/desru/README.md @@ -39,6 +39,58 @@ fn main() { } ``` +### Clock + +Inspired by the simple clock example in the SimPy documentation. + + +```rust +use desru::{Event, EventScheduler}; + +fn clock(scheduler: &mut EventScheduler, name: String, tick: f64) { + // Function to handle the clock's actions and schedule the next tick + fn action(scheduler: &mut EventScheduler, name: String, tick: f64) { + // Print the name of the clock and the current simulation time + println!("{}: {}", name, scheduler.current_time); + + // Schedule the next tick of the clock + let next_time = scheduler.current_time + tick; + let event = Event::new( + next_time, + Some(Box::new(move |scheduler: &mut EventScheduler| { + action(scheduler, name.clone(), tick); + None + })), + None, + ); + scheduler.schedule(event); + } + + // Schedule the first event for the clock at time 0 + scheduler.schedule(Event::new( + 0.0, + Some(Box::new(move |scheduler: &mut EventScheduler| { + action(scheduler, name.clone(), tick); + None + })), + None, + )); +} + +fn main() { + // Initialize the event scheduler + let mut scheduler = EventScheduler::new(); + + // Schedule initial clock processes + clock(&mut scheduler, "fast".to_string(), 0.5); + clock(&mut scheduler, "slow".to_string(), 1.0); + + // Run the scheduler until the maximum simulation time + scheduler.run_until_max_time(2.0); +} +``` + + ### Simple Car Process This example replicates the classic SimPy Car simulation, where a car alternates between parking and driving.