3 releases
Uses new Rust 2024
| 0.1.2 | Sep 7, 2025 |
|---|---|
| 0.1.1 | Sep 5, 2025 |
| 0.1.0 | Sep 5, 2025 |
#458 in Game dev
74 downloads per month
13KB
198 lines
This crate provides the BackgroundRunner struct, which runs a
given task in the background once [BackgroundRunner::update()] is called.
use background_runner::BackgroundRunner;
use std::thread::sleep;
use std::time::Duration;
use std::time::Instant;
let mut runner_iter = 0;
// Set up the runner, giving it a task to run
let runner = BackgroundRunner::new(move |iter| {
// Simulate some heavy work
println!("runner_iter = {runner_iter}, iter = {iter}");
runner_iter += 1;
sleep(Duration::from_millis(10));
});
let start = Instant::now();
let mut iter = 0;
while start.elapsed().as_millis() < 100 {
// Update the runner with the current loop iteration
runner.update(&iter);
iter += 1;
}
Background Runner
The purpose of this crate is to run a heavy task in the background multiple times without blocking the triggering thread. The motivating use case is to periodically write to a file from a game loop.
// Create a background runner and give it a task to run
let runner = BackgroundRunner::new(move |state| {
// Heavy work goes here
});
// Some state to repeatedly pass to the runner.
// This can be anything that's Send + 'static
let state = 42;
loop {
// Light work goes here
// Trigger the runner if it's not busy currently
runner.update(&state);
}
The update() method is guaranteed to never block the calling thread. It will only trigger the runner's task if it's not currently running (i.e. busy with processing a previous run request).