Running a background task with Rocket

#1

Say I have a Rocket app with some in-memory state like:

rocket::ignite()
    .manage(Cache::new())
    .launch();

And since it’s Send + Sync, it can be read by multiple request handlers on different threads at the same time:

#[get("/")]
fn index(cache: State<Cache>) -> Html { ... }

But now say I want to clear out old entries from the cache every 5 minutes. I already moved the Cache into the Rocket app, so I can’t keep hold of it and run this in another thread. I could define an endpoint for it:

#[get("/clear_cache")]
fn clear_cache(cache: State<Cache>) -> Status { cache.clear() }

But then I’d have to run some separate process just to make HTTP calls to this service, which seems messier than it should be.

So my question is: is there a way within Rocket to run background tasks that can access managed State?

#2

I’d don’t know much about racket or what Cache is, but documentation says that anything managed must implement Send+Sync, so you could just create a thread and pass there cache as well.
The thread would wait 5 min and clear the cache in infinite loop.