atomic-timer

Crates.ioatomic-timer
lib.rsatomic-timer
version0.2.2
created_at2024-12-22 22:43:55.450975+00
updated_at2025-01-14 18:26:48.596832+00
descriptionAtomic timer for Rust
homepage
repositoryhttps://github.com/roboplc/atomic-timer
max_upload_size
id1492329
size18,330
Sergiy S. (divi255)

documentation

README

atomic-timer - an atomic timer for Rust crates.io page docs.rs page GitHub Actions CI

A passive timer object which can be manipulated atomically. Useful for automation and robotics tasks.

Atomic timer is a part of RoboPLC project.

Usage example

Basic usage

use atomic_timer::AtomicTimer;
use std::time::Duration;

let timer = AtomicTimer::new(Duration::from_secs(1));
for _ in 0..100 {
    if timer.expired() {
        println!("Timer expired");
        timer.reset(); // does not need to be mutable
    } else {
        println!("Elapsed: {:?}, remaining: {:?}", timer.elapsed(), timer.remaining());
    }
    // do some work
}

Multi-threaded usage

use atomic_timer::AtomicTimer;
use std::sync::Arc;
use std::time::Duration;

let timer = Arc::new(AtomicTimer::new(Duration::from_secs(1)));
for _ in 0..10 {
    let timer = timer.clone();
    std::thread::spawn(move || {
        for _ in 0..100 {
            if timer.reset_if_expired() {
                println!("Timer expired");
                // react to the timer expiration
                // guaranteed to be true only for one thread
            }
            // do some other work
        }
    });
}

Serialization / deserialization

Atomic timer objects can be safely serialized and de-serialized (requires serde feature).

When a timer is de-serialized, it keeps its state (elapsed/remaining time), despite the system monotonic clock difference.

MSRV

1.68.0

Commit count: 12

cargo fmt