summaryrefslogtreecommitdiffstats
path: root/tokio/src/time/interval.rs
diff options
context:
space:
mode:
authorCraig Pastro <siyopao@gmail.com>2020-06-16 18:25:08 +0900
committerGitHub <noreply@github.com>2020-06-16 11:25:08 +0200
commite2adf2612d215d1925ef0dd9e2aa8cdd4c825abc (patch)
treedfb42811a4854ad6477a519573b5dd368ee76982 /tokio/src/time/interval.rs
parent2bc6bc14a82dc4c8d447521005e044028ae199fe (diff)
time: add example using `interval` to the time module (#2623)
Diffstat (limited to 'tokio/src/time/interval.rs')
-rw-r--r--tokio/src/time/interval.rs31
1 files changed, 31 insertions, 0 deletions
diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs
index 090e2d1f..1fa21e66 100644
--- a/tokio/src/time/interval.rs
+++ b/tokio/src/time/interval.rs
@@ -33,6 +33,37 @@ use std::task::{Context, Poll};
/// // approximately 20ms have elapsed.
/// }
/// ```
+///
+/// A simple example using `interval` to execute a task every two seconds.
+///
+/// The difference between `interval` and [`delay_for`] is that an `interval`
+/// measures the time since the last tick, which means that `.tick().await`
+/// may wait for a shorter time than the duration specified for the interval
+/// if some time has passed between calls to `.tick().await`.
+///
+/// If the tick in the example below was replaced with [`delay_for`], the task
+/// would only be executed once every three seconds, and not every two
+/// seconds.
+///
+/// ```
+/// use tokio::time;
+///
+/// async fn task_that_takes_a_second() {
+/// println!("hello");
+/// time::delay_for(time::Duration::from_secs(1)).await
+/// }
+///
+/// #[tokio::main]
+/// async fn main() {
+/// let mut interval = time::interval(time::Duration::from_secs(2));
+/// for _i in 0..5 {
+/// interval.tick().await;
+/// task_that_takes_a_second().await;
+/// }
+/// }
+/// ```
+///
+/// [`delay_for`]: crate::time::delay_for()
pub fn interval(period: Duration) -> Interval {
assert!(period > Duration::new(0, 0), "`period` must be non-zero.");