我有一个要定期检查和修剪的缓存.在Java中,我将执行以下操作:
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();当然,我将线程安全类型用作高速缓存时会遇到一些问题,但撇开这个问题,我的问题很简单. Scala运行重复后台任务的方式是什么-您不想在应用程序的主线程中运行某些东西?
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?
我已经使用了一些actor,我想在这种情况下我的问题是我没有任何东西可以生成一条消息,表明该是时候清除缓存了.或者更确切地说,我能想到的生成这些消息的唯一方法是创建一个线程来执行此操作...
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...
我需要人们对答案进行投票-他们对我来说都很好
推荐答案有很多方法可以做到这一点,但我会做一些简单的事情,如下所示.
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 } }希望这会有所帮助.
更多推荐
Scala中的后台任务
发布评论