changeset 607:282fae1c12e4 rust

NotTooOften
author Matt Johnston <matt@ucc.asn.au>
date Fri, 17 Feb 2017 22:27:44 +0800
parents 3c1d37d78415
children 71f045231a07
files rust/src/main.rs
diffstat 1 files changed, 27 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/rust/src/main.rs	Fri Feb 17 21:38:45 2017 +0800
+++ b/rust/src/main.rs	Fri Feb 17 22:27:44 2017 +0800
@@ -18,6 +18,9 @@
 extern crate docopt;
 
 use std::io;
+use std::time::{Duration,Instant};
+use std::ops::Not;
+use std::cell::Cell;
 
 use tokio_core::reactor::Core;
 use futures::{Stream,Sink,Future};
@@ -173,3 +176,27 @@
     run(&config, args.flag_nowait, args.flag_test);
 }
 
+/// Call closures with a rate limit. Useful for log message ratelimiting
+pub struct NotTooOften {
+    last: Cell<Instant>,
+    limit: Duration,
+}
+
+impl NotTooOften {
+    pub fn new(limit_secs: u64) -> Self {
+        NotTooOften {
+            limit: Duration::new(limit_secs, 0),
+            last: Cell::new(Instant::now() - Duration::new(limit_secs+1, 0)),
+        }
+    }
+
+    pub fn and_then<F>(&self, op: F)
+        where F: Fn() {
+        let now = Instant::now();
+        if now - self.last.get() > self.limit {
+            self.last.set(now);
+            op();
+        }
+    }
+}
+