2012-03-15 32 views

回答

54

你並不真的需要一個演員要做到這一點在阿卡1.3.1你可以安排一個功能每5分鐘被稱爲像這樣:

Scheduler.schedule(() => println("Do something"), 0L, 5L, TimeUnit.MINUTES) 

但是,如果你希望它是其他原因一個演員如果你使用的阿卡2.0,那麼你會這樣稱呼它

case class Message() 

val actor = actorOf(new Actor { 
    def receive = { 
    case Message() => println("Do something in actor") 
    } 
}).start() 

Scheduler.schedule(actor, Message(), 0L, 5L, TimeUnit.MINUTES) 

它會像這樣

val system = ActorSystem("MySystem") 
system.scheduler.schedule(0 seconds, 5 minutes)(println("do something")) 
完成

或發送消息給一個演員,每5分鐘這樣的

case class Message() 
class MyActor extends Actor { 
    def receive = { case Message() => println("Do something in actor") } 
} 

val system = ActorSystem("MySystem") 
val actor = system.actorOf(Props(new MyActor), name = "actor") 
system.scheduler.schedule(0 seconds, 5 minutes, actor, Message()) 
+3

Scheduler.schedule似乎不存在了 – Phil 2016-05-13 13:54:16

+0

牢記你可能想知道前面的調用在新車在5分鐘後起火之前完成其程序,至少在某些情況下是如此。你可以使用帶有一些額外邏輯的'scheduleOnce'。 – matanster 2016-07-13 06:16:12

19

使用日程表的方法是一個很好的方法,雖然有對消息排隊一個潛在的,如果按計劃完成的工作是如此之大它可能需要比預定的時間間隔更長的時間。如果你想結束一個迭代的開始下一個之間發生的時間間隔,然後使用scheduleOnce有以下模式:

import akka.actor.Actor 
import scala.concurrent.duration._ 

class SchedulingActor extends Actor { 

    override def preStart(): Unit = { 
    self ! "Do Some Work" 
    } 

    def receive = { 
    case "Do Some Work" => 
     doWork 
     context.system.scheduler.scheduleOnce(5 minutes, self, "Do Some Work") 
    } 

    def doWork = ??? 
} 
+2

這是2016年的相關答案。Scheduler.schedule不再是有效的方法。 – Zee 2016-05-26 13:01:48

+0

難道你不能只使用'context.system.scheduler.schedule(...)'每5分鐘發送一次消息給'self'嗎?它看起來會更乾淨,並且不需要重寫'preStart'。 – 2017-06-05 19:49:39

+0

@BranislavLazic不,不設置循環時間表的目的是避免向演員發送另一條消息,前提是處理邏輯需要超過每個預定消息之間的時間間隔的時間。通過scheduleOnce(),演員可以在需要的時間內完成任何需要的工作,然後在安全的情況下設置另一個時間表來發送未來消息給自己。對於某些情況,這可以避免死鎖和其他併發問題。 – speby 2017-07-19 03:00:04

0

如果有人要的Java代碼,然後他們可以這樣做

Cancellable cancellable = system.scheduler().schedule(Duration.Zero(), Duration.create(5, TimeUnit.MINUTES), cronActor, "tick", system.dispatcher(), null); 
相關問題