ttl/
ttl.rs

1use std::path::Path;
2use std::thread::sleep;
3use std::time::Duration;
4use epoch_db::DB;
5
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let db = DB::new(Path::new("./my_database"))?;
8
9    // Set a key with a 2-second TTL
10    db.set("session:123", "user_token", Some(Duration::from_secs(2)))?;
11    println!("'session:123' is set.");
12
13    // The key exists initially
14    assert!(db.get("session:123")?.is_some());
15
16    // Wait for the TTL to expire
17    sleep(Duration::from_secs(3));
18
19    // The key should now be gone
20    assert!(db.get("session:123")?.is_none());
21    println!("'session:123' has expired.");
22
23    // You can also update a key to make it permanent
24    db.set(
25        "user:permanent",
26        "This will last forever",
27        Some(Duration::from_secs(1)),
28    )?;
29    db.set("user:permanent", "This will last forever", None)?; // Remove the TTL
30
31    sleep(Duration::from_secs(2));
32    assert!(db.get("user:permanent")?.is_some());
33    println!("'user:permanent' is still here.");
34
35    Ok(())
36}