Skip to content

Instantly share code, notes, and snippets.

@octave99
Created April 7, 2019 16:55
Show Gist options
  • Save octave99/2d23b279f36db22325cee0ce82c63973 to your computer and use it in GitHub Desktop.
Save octave99/2d23b279f36db22325cee0ce82c63973 to your computer and use it in GitHub Desktop.
use futures::{
future::{lazy, ok, Future},
Async, Poll,
};
use std::time::Duration;
use tokio;
use tokio_timer::sleep;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
pub struct Service {
running: Arc<AtomicBool>,
}
impl Service {
fn new(running: Arc<AtomicBool>) -> Self {
Service { running }
}
}
impl Future for Service {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.running.load(Ordering::Relaxed) {
print!(".");
futures::task::current().notify();
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
}
fn start(running: Arc<AtomicBool>) -> impl Future<Item = (), Error = ()> {
Service::new(running).and_then(|_| ok(()))
}
fn stop(running: Arc<AtomicBool>) -> impl Future<Item = (), Error = ()> {
sleep(Duration::from_millis(1))
.and_then(move |_| {
print!("\nStopping\n");
running.store(false, Ordering::Relaxed);
ok(())
})
.map_err(|_| ())
}
fn main() {
tokio::run(lazy(|| {
let running = Arc::new(AtomicBool::new(true));
print!("Starting\n");
tokio::spawn(start(running.clone()));
print!("Started\n");
tokio::spawn(stop(running));
ok(())
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment