Trait minion::Cancellable
[−]
[src]
pub trait Cancellable { type Error; fn for_each(&mut self) -> Result<LoopState, Self::Error>; fn run(&mut self) -> Result<(), Self::Error> { ... } fn spawn(self) -> Handle<Self::Error>
where
Self: Sized + Send + 'static,
Self::Error: Send + 'static, { ... } }
A service that implements Cancellable
can be told to stop accepting new work at any time, and
will return at the first following opportunity.
More concretely, it emulates a loop like the following:
loop { // fetch some work // do some work that might error }
But where the loop
can be "cancelled". That is, after the next piece of work is processed, no
more work is handled, and the loop breaks.
This trait provides two main methods, [Cancellable::run
] and [Cancellable::spawn
]. The
former runs the loop on the current thread (and thus blocks it). The latter spawns a new
thread, and executes the loop on that thread. Only loops started using spawn
can be
cancelled.
For example, the implementation below shows how a classic server accept loop could be turned
into a cancellable accept loop. If [Handle::cancel
] is called, then at most one more
connection will be accepted before the loop returns and [Handle::wait
] would too.
struct Service(net::TcpListener); impl Cancellable for Service { type Error = io::Error; fn for_each(&mut self) -> Result<minion::LoopState, Self::Error> { let mut stream = self.0.accept()?.0; write!(stream, "hello!\n")?; Ok(minion::LoopState::Continue) } } impl Service { fn new() -> io::Result<Self> { Ok(Service(net::TcpListener::bind("127.0.0.1:6556")?)) } } fn main() { Service::new()?.run()?; }
Associated Types
type Error
Error type for [Cancellable::for_each
].
Required Methods
fn for_each(&mut self) -> Result<LoopState, Self::Error>
This method is called once for every iteration of the loop.
If it errors, the outer service loop will also return with that same error.
If it returns a LoopState
, the service loop will continue or break accordingly.
If it panics, the panic will be propagated to the waiting thread.
Provided Methods
fn run(&mut self) -> Result<(), Self::Error>
Continuously execute [Cancellable::for_each
] until it returns an error or a
[LoopState::Break
].
fn spawn(self) -> Handle<Self::Error> where
Self: Sized + Send + 'static,
Self::Error: Send + 'static,
Self: Sized + Send + 'static,
Self::Error: Send + 'static,
Continuously execute [Cancellable::for_each
] in a new thread, and return a [Handle
] to
that loop so that it can be cancelled or waited for.