comparison rust/src/main.rs @ 607:282fae1c12e4 rust

NotTooOften
author Matt Johnston <matt@ucc.asn.au>
date Fri, 17 Feb 2017 22:27:44 +0800
parents 278f1002b5c7
children 7bda01659426
comparison
equal deleted inserted replaced
606:3c1d37d78415 607:282fae1c12e4
16 extern crate toml; 16 extern crate toml;
17 17
18 extern crate docopt; 18 extern crate docopt;
19 19
20 use std::io; 20 use std::io;
21 use std::time::{Duration,Instant};
22 use std::ops::Not;
23 use std::cell::Cell;
21 24
22 use tokio_core::reactor::Core; 25 use tokio_core::reactor::Core;
23 use futures::{Stream,Sink,Future}; 26 use futures::{Stream,Sink,Future};
24 use futures::sync::{mpsc}; 27 use futures::sync::{mpsc};
25 use sensor::Sensor; 28 use sensor::Sensor;
171 } 174 }
172 175
173 run(&config, args.flag_nowait, args.flag_test); 176 run(&config, args.flag_nowait, args.flag_test);
174 } 177 }
175 178
179 /// Call closures with a rate limit. Useful for log message ratelimiting
180 pub struct NotTooOften {
181 last: Cell<Instant>,
182 limit: Duration,
183 }
184
185 impl NotTooOften {
186 pub fn new(limit_secs: u64) -> Self {
187 NotTooOften {
188 limit: Duration::new(limit_secs, 0),
189 last: Cell::new(Instant::now() - Duration::new(limit_secs+1, 0)),
190 }
191 }
192
193 pub fn and_then<F>(&self, op: F)
194 where F: Fn() {
195 let now = Instant::now();
196 if now - self.last.get() > self.limit {
197 self.last.set(now);
198 op();
199 }
200 }
201 }
202