Tokio: Question: Interval usage of tokio-timer v0.2.0

Created on 31 Mar 2018  路  7Comments  路  Source: tokio-rs/tokio

in v0.1.x I created an interval like this:

 let loop_interval = Timer::default().interval(Duration::from_millis(2000)); 

in v0.2.0 I changed it to:

 let loop_interval = Interval::new(Instant::now(),Duration::from_millis(2000));

but now I get an "timer is shutdown" error :(
What's the correct usage now to avoid this error?

Most helpful comment

Right. It would be great if we had an example of usage of timer in examples/ dir.

All 7 comments

Ah yes, with the timer v0.2.0, you must create the timer yourself and schedule running it.

You can create a timer yourself, get the handle, and then do handle.interval(...).

You would need to spawn up a background thread yourself to run this timer. I did not implement that logic (yet?) in the new release.

You could also use tokio's Runtime which manages all of that for you.

Can you elaborate on this a bit, @carllerche. I tried to setup a timer, but I have no idea how to get the reactor. Do I need a new reactor or can I use the 'default reactor'?

Right. It would be great if we had an example of usage of timer in examples/ dir.

@manuels This page should help: https://tokio.rs/docs/going-deeper/timers/#interval

If you still run into issues, let me know as it is something lacking in those docs.

I think we can close this now.
The main difference to me was to use tokio::run(task) instead of core.run(task).

@carllerche page is now 404, where could we find an example?

If you are getting an timer is shutdown or similar error, it is because you created the timer from outside the runtime. You should either move creation into an async fn, or you can use the enter method to enter the runtime, and create it there.

let interval = runtime.enter(|| interval(duration));

(or if you just have an Handle, you can use handle.enter)

Was this page helpful?
0 / 5 - 0 ratings