Querying state of a background task


#1

I’m trying to implement the following system:

  • A top level Activity is given a set of Jobs, which are arbitrary logic to run.
  • When the top level activity is called, it runs the jobs which can be in parallel — they should not depend on each other.
  • While the jobs are running, the activity polls them regularly (e.g. every 100 ms) to check their current state.
  • There are a set of Views which display application state. These views should be updated with the state of the jobs each time the activity wakes up.

I was intending for the job state to contain mutable information, like number of units complete, or description of “what it is doing now”.

Is it possible / a good candidate to implement this with futures-rs? The API doesn’t look like it supports passing an updatable state of the job to the caller (either using futures_cpupool or tokio_core).

Here’s a playground link / gist to a stripped down version of where I got to. Specifically line 69’s TODO: is where the design questions became difficult / “need some rust expert to guide me”.

I guess an ideal mechanism is whenever the Job/Future/Task-like-thing is polled, it can return Result<Async::Complete<State, ()>, Result<Async::NotReady<State, ()>, or an error, so that there isn’t a need for an Arc<Mutex<State>> somewhere, if that is possible.


#2

I am not sure that this would be easy to achieve: if the job is running, it needs to be interrupted to respond to the poll event.

I think it would be easier if jobs instead published their state, like this;

impl Job {
  fn do_work(&mut self, progress: ProgressIndicator) {
    ...
    progress.send_update(Update::StartPhase { name: "shaving the yaks", ... })  
    ...
  }
}

To actually gather the updates of the jobs, I think ::std::sync::mpsc would be a perfect fit.

Each job get’s it’s unique ProgressIndicator, which holds a Sender inside. The Activity will then drain Receiver and push updates to the Views.