Skip to content

Commit de3c729

Browse files
svenstaroMatheus Xavier
authored andcommitted
Add tokio example
1 parent cb46f79 commit de3c729

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,6 @@ categories = ["os::unix-apis"]
1616
libc = "0.2.113"
1717
nix = {version = "0.29.0", features = ["process", "user", "fs"]}
1818
thiserror = "2.0.12"
19+
20+
[dev-dependencies]
21+
tokio = { version = "1.45.0", features = ["rt", "rt-multi-thread", "time"] }

examples/tokio.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use std::{fs::File, time::Duration};
2+
3+
use daemonize_me::Daemon;
4+
use tokio::{
5+
runtime::Runtime,
6+
time::{sleep, Instant},
7+
};
8+
9+
// We can't use #[tokio::main] here!
10+
// We need to daemonize first and only then may we initialize the tokio runtime.
11+
fn main() {
12+
let stdout = File::create("info.log").unwrap();
13+
let stderr = File::create("err.log").unwrap();
14+
let daemon = Daemon::new()
15+
.pid_file("example.pid", Some(false))
16+
.work_dir(".")
17+
.stdout(stdout)
18+
.stderr(stderr)
19+
.start();
20+
21+
match daemon {
22+
Ok(_) => println!("Daemonized with success"),
23+
Err(e) => eprintln!("Error, {}", e),
24+
}
25+
26+
let rt = Runtime::new().unwrap();
27+
rt.block_on(async {
28+
let now = Instant::now();
29+
println!("Before async sleep, elapsed: {}", now.elapsed().as_secs());
30+
sleep(Duration::from_secs(5)).await;
31+
println!("After async sleep, elapsed: {}", now.elapsed().as_secs());
32+
});
33+
34+
println!("Finished execution");
35+
}

0 commit comments

Comments
 (0)