pub struct BackgroundRunner<T> { /* private fields */ }Expand description
Runner for a background task to be invoked periodically.
Implementations§
Source§impl<T: 'static + Send> BackgroundRunner<T>
impl<T: 'static + Send> BackgroundRunner<T>
Sourcepub fn new(task: impl 'static + Send + FnMut(&T)) -> Selfwhere
T: Default,
pub fn new(task: impl 'static + Send + FnMut(&T)) -> Selfwhere
T: Default,
Create a new background runner with the given task
This spawns a new thread to execute the task periodically, triggered by the Self::update() method.
Examples found in repository?
6fn main() {
7 let mut runner_iter = 0;
8
9 // Set up the runner, giving it the task to run
10 let runner = BackgroundRunner::new(move |iter| {
11 // Simulate some heavy work
12 sleep(Duration::from_millis(10));
13 println!("runner_iter = {runner_iter}, iter = {iter}");
14 runner_iter += 1;
15 });
16
17 let start = Instant::now();
18 let mut iter = 0;
19 while start.elapsed().as_millis() < 100 {
20 // Update the runner with the current loop iteration
21 runner.update(&iter);
22 iter += 1;
23 }
24}Sourcepub fn with_init_data(
init_data: T,
task: impl 'static + Send + FnMut(&T),
) -> Self
pub fn with_init_data( init_data: T, task: impl 'static + Send + FnMut(&T), ) -> Self
Create a new background runner with the given initial data and task
This spawns a new thread to execute the task periodically, triggered by the Self::update() method.
Sourcepub fn update(&self, new_data: &T)where
T: Clone,
pub fn update(&self, new_data: &T)where
T: Clone,
Trigger the runner’s task if it’s not currently running.
This will never block the current thread. If the task is currently running and thus not able to process this update request, nothing will be done and this method returns immediately.
T::clone_from() is invoked to update the data that is passed to the task.
Examples found in repository?
6fn main() {
7 let mut runner_iter = 0;
8
9 // Set up the runner, giving it the task to run
10 let runner = BackgroundRunner::new(move |iter| {
11 // Simulate some heavy work
12 sleep(Duration::from_millis(10));
13 println!("runner_iter = {runner_iter}, iter = {iter}");
14 runner_iter += 1;
15 });
16
17 let start = Instant::now();
18 let mut iter = 0;
19 while start.elapsed().as_millis() < 100 {
20 // Update the runner with the current loop iteration
21 runner.update(&iter);
22 iter += 1;
23 }
24}Sourcepub fn update_with(&self, f: impl FnOnce(&mut T))
pub fn update_with(&self, f: impl FnOnce(&mut T))
Trigger the runner’s task if it’s not currently running.
This will never block the current thread. If the task is currently running and thus not able to process this update request, nothing will be done and this method returns immediately.
The given closure is invoked with a mutable reference to the currently stored data to allow for its modification