ttl/
ttl.rs

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