scala – 用Akka在一天中的固定时间安排任务
发布时间:2020-12-16 09:13:53 所属栏目:安全 来源:网络整理
导读:我是Akka的初学者我需要在一天的固定时间安排一个任务,就像上午8点.我知道如何做是定期安排任务,例如 import akka.util.duration._scheduler.schedule(0 seconds,10 minutes) { doSomething()} What is the simplest way to schedule tasks at fixed times o
我是Akka的初学者我需要在一天的固定时间安排一个任务,就像上午8点.我知道如何做是定期安排任务,例如
import akka.util.duration._ scheduler.schedule(0 seconds,10 minutes) { doSomething() }
一个小圆括号 使用这个功能很容易做到我想要的.一个玩具的实现将会是这样的 scheduler.schedule(0 seconds,24 hours) { val now = computeTimeOfDay() val delay = desiredTime - now scheduler.scheduleOnce(delay) { doSomething() } } 这并不困难,但是我引入了一点竞争条件.事实上,考虑到如果我在8点之前发布,会发生什么.外部关闭将开始,但是当我计算延迟时间,我们可能是在8AM之后.这意味着立即执行的内部关闭将被推迟到明天,从而跳过执行一天. 有一些方法可以解决这个竞争状况:例如我可以每12个小时执行一次检查,而不是立即安排任务,将其发送给不能一次接受多个任务的演员. 但是可能这已经存在于Akka或者一些扩展. 解决方法
写一次,每天运行
val GatherStatisticsPeriod = 24 hours private[this] val scheduled = new AtomicBoolean(false) def calcBeforeMidnight: Duration = { // TODO implement } def preRestart(reason: Throwable,message: Option[Any]) { self ! GatherStatisticsScheduled(scheduled.get) super.preRestart(reason,message) } def schedule(period: Duration,who: ActorRef) = ServerRoot.actorSystem.scheduler .scheduleOnce(period)(who ! GatherStatisticsTick) def receive = { case StartServer(nodeName) => sender ! ServerStarted(nodeName) if (scheduled.compareAndSet(false,true)) schedule(calcBeforeMidnight,self) case GatherStatisticsTick => stats.update scheduled.set(true) schedule(GatherStatisticsPeriod,self) case GatherStatisticsScheduled(isScheduled) => if (isScheduled && scheduled.compareAndSet(false,isScheduled)) schedule(calcBeforeMidnight,self) } 我相信Akka的调度器可以以内部方式处理重新启动.我用不间断的方式发送消息给自己 – 实际上没有严格的交货保证.此外,tick可能会有所不同,所以GatherStatisticsPeriod可能是一个功能. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |