Scala中的后台任务

时间:2011-06-13 18:27:26

标签: multithreading scala

我有一个缓存,我想定期检查和修剪。在Java中,我会执行以下操作:

new Thread(new Runnable() {
  void run() {
    while (true) { 
      Thread.sleep(1000);
      // clear the cache's old entries
    }
  }
}).start();

当然,我有一些线程安全类型的问题可以用作缓存,但是把它放在一边,我的问题很简单。什么是Scala运行定期后台任务的方式 - 您不希望在应用程序的主线程中运行?

我曾经使用过一些演员,我猜我在这个场景中遇到的问题是我没有任何东西可以生成消息,是时候清除缓存了。或者更确切地说,我可以想象生成这些消息的唯一方法是创建一个线程来执行它...

编辑:我需要人们对答案进行投票 - 他们看起来都很好

6 个答案:

答案 0 :(得分:24)

有很多方法可以做到这一点,但我会做一些简单的事情,如下所示。

import scala.concurrent.ops._

spawn {
  while (true) { 
    Thread.sleep(1000);
    // clear the cache's old entries
  }
}

希望这有帮助。

答案 1 :(得分:11)

您可以使用Akka Scheduler,它允许您向执行该作业的(akka)演员发送定期消息。从文档中,只需使用:

import akka.actor.Scheduler

//Sends messageToBeSent to receiverActor after initialDelayBeforeSending and then after each delayBetweenMessages
Scheduler.schedule(receiverActor, messageToBeSent, initialDelayBeforeSending, delayBetweenMessages, timeUnit)

答案 2 :(得分:8)

期货是一种简单的方法,无需显式启动新线程

import scala.actors.Futures._

// main thread code here

future {
   // second thread code here
}

// main thread code here

答案 3 :(得分:7)

spawn很好,但请注意您的示例代码也适用于Scala:

new Thread(new Runnable() {
  override def run() {
    while (true) { 
      Thread.sleep(1000);
      // clear the cache's old entries
    }
  }
}).start();

只需使用隐式转换清理它:

implicit def funcToRunnable(f: => ()) = new Runnable() { override def run() { f() } }

new Thread{
  while(true) {
    Thread.sleep(1000);
    // blah
  }
}.start()

答案 4 :(得分:5)

Actors没有占用线程:

import actors.{TIMEOUT, Actor}
import actors.Actor._

private case class Ping( client: Actor, update: Int )
private case class Pulse()
case class Subscribe( actor: Actor )
case class Unsubscribe( actor: Actor )

class PulseActor extends Actor {
  def act = eventloop {
        case ping: Ping => { sleep(ping.update); ping.client ! Pulse }
  }
  def sleep(millis: Long) =
    receiveWithin(millis) {
      case TIMEOUT =>
  }
}

class ServiceActor extends Actor {

  var observers: Set[Actor] = Set.empty
  val pulseactor = new PulseActor
  val update = 2000

  def act = {
    pulseactor.start
    pulseactor ! new Ping( this, update )
    loop {
      react {
        case sub: Subscribe => observers += sub.actor
        case unsub: Unsubscribe => observers -= unsub.actor
        case Pulse => pulse
      }
    }
  }


  def pulse {  
    //cpuload = CPUprofile.getCPUload.getOrElse{ List(0.0) }  //real work
    observers foreach { observer => observer ! "CPUloadReport( cpuload )" }
    pulseactor ! Ping(this, update)
  }
}

object Exercise extends App {
  val deamon = new ServiceActor
  deamon.start
}

答案 5 :(得分:4)

从Scala 2.11.x开始,Akka演员似乎是最好的方式来做这个恕我直言。首先创建一个任务调度库:

import akka.actor.ActorSystem
import scala.language.postfixOps
import scala.concurrent.duration._
val actorSystem = ActorSystem()
val scheduler = actorSystem.scheduler
implicit val executor = actorSystem.dispatcher

// do once after period millis
def doOnce(fn: => Unit, period:Long) = scheduler.scheduleOnce(period milliseconds)(fn) 
// do regularly every period millis starting now
def doRegularly(fn: => Unit, period:Long) = scheduler.schedule(0 seconds, period milliseconds)(fn)
// do regularly every period millis if whileFn is true, starting now 
def doWhile(fn: => Unit, whileFn: => Boolean, period:Long) {
 if (whileFn) {
    fn
    doOnce(doWhile(fn, whileFn, period), period)
 }
}

然后将其用作:

doRegularly({
  println("hello world!")
}, 1000) // repeat every 1000 millisecs

doWhile({
  println("Sleeping!")
}, whileDaylight, 1000) // repeat every 1000 millisecs whileDaylight is true