通过例子学习Rust

42 定时器

A Timer represents an underlying OS timer, and can generate one-shot and periodic notifications via the Receiver endpoint of a channel.

use std::io::Timer; use std::io::timer; use std::time::duration::Duration; use std::iter; fn main() { let interval = Duration::milliseconds(1000); // Create a timer object let mut timer = Timer::new().unwrap(); // Create a one-shot notification // (superfluous type annotation) let oneshot: Receiver<()> = timer.oneshot(interval); println!("Wait {} ms...", interval.num_milliseconds()); // Block the task until notification arrives oneshot.recv(); println!("Done"); println!("Sleep for {} ms...", interval.num_milliseconds()); // This is equivalent to `timer.oneshot(interval).recv()` timer::sleep(interval); println!("Done"); // The same timer can be used to generate periodic notifications // (superfluous type annotation) let metronome: Receiver<()> = timer.periodic(interval); println!("Countdown"); for i in iter::range_step(5i, 0, -1) { // This loop will run once every second metronome.recv(); println!("{}", i); } metronome.recv(); println!("Ignition!"); }

The playpen has a time limit, so you won't be able to see the (full) output in the editor. Here's the output you should see, if you run this in a computer.

$ rustc timers.rs && time ./timers
Wait 1000 ms...
Done
Sleep for 1000 ms...
Done
Countdown
5
4
3
2
1
Ignition!
./timers  0.00s user 0.00s system 0% cpu 8.003 total