I have a cache I want to periodically check and prune. In Java, I'd do the following:
new Thread(new Runnable() { void run() { while (true) { Thread.sleep(1000); // clear the cache's old entries } } }).start();
Sure, I'd have some issues with thread-safe types to use as the cache, but putting that aside, my question is simple. What's the Scala way of running a recurring background task -- something you don't want running in the application's main thread?
I've used actors a bit and I guess my problem in this scenario is that I don't have anything to generate a message that it's time to clear the cache. Or rather, the only way I can imagine to generate those messages is to create a thread to do it...
EDIT: I need people to vote on answers -- they all look good to me
There are many ways to do that, but I would do something simple like the following.
import scala.concurrent.ops._ spawn { while (true) { Thread.sleep(1000); // clear the cache's old entries } }
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With