score:7
Write once, run everyday
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)
}
I believe that Akka's scheduler handles restarts internally, one way or another. I used non-persistent way of sending a message to self - actually no strict guarantee of delivery. Also, ticks may vary, so GatherStatisticsPeriod might be a function.
score:1
Just to add another way to achieve it, this can be done using Akka Streams by ticking a message and filtering on time.
Source
.tick(0.seconds, 2.seconds, "hello") // emits "hello" every two seconds
.filter(_ => {
val now = LocalDateTime.now.getSecond
now > 20 && now < 30 // will let through only if the timing is right.
})
.runForeach(n => println("final sink received " + n))
score:6
To use this kind of scheduling in Akka, you would have to roll your own or maybe use Quartz, either through Akka Camel or this prototype quartz for akka.
If you don't need anything fancy and extremely accurate, then I would just calculate the delay to the desired first time and use that as the start delay to the schedule call, and trust the interval.
score:6
Let's say you want to run your task every day at 13 pm.
import scala.concurrent.duration._
import java.time.LocalTime
val interval = 24.hours
val delay = {
val time = LocalTime.of(13, 0).toSecondOfDay
val now = LocalTime.now().toSecondOfDay
val fullDay = 60 * 60 * 24
val difference = time - now
if (difference < 0) {
fullDay + difference
} else {
time - now
}
}.seconds
system.scheduler.schedule(delay, interval)(doSomething())
Also remember that server timezone may be different from yours.
Source: stackoverflow.com
Related Query
- Scheduling a task at a fixed time of the day with Akka
- What's the best way to wrap a monix Task with a start time and end time print the difference?
- Do I need to re-use the same Akka ActorSystem or can I just create one every time I need one?
- What is the best way to work with akka from nodejs
- Scala Case Classes vs. Protocol Buffers with Akka over the network
- How to profile the time spent for a task in SBT
- Scala: Calculating the Moving Sum of a List with a fixed window
- Is the Akka Actors library installed with the Scala IDE for Scala 2.10?
- The actor pattern with Akka and long running processes
- Akka Streams. Control The Number of Items Being Processed in Akka Streams At One Time
- Akka Scheduler, error with time unit
- Any way to log akka timeouts with more information about where the error is?
- zip-compress a List[Source[ByteString, NotUsed]] on the fly with Akka Streams
- Does the ask pattern work with Akka IO actors?
- Scala task parallelization with actors => How does the scheduler work?
- How to write stream to S3 with year, month and day of the day when records were received?
- Scala - schedule a task at a given time of the day: run a task everyday at 6pm
- How to create variable with the first day of current month in Databricks Spark Scala?
- NextExecution time with quartz definition fails when date if the end of the month
- The idiomatic way to manage shared state with Akka Streams
- What's the minimal code required to have two local instances communicate with Akka actors?
- How to mock some methods only throw exception for the first time and then do nothing, with specs2?
- How to work with the sender ActorRef in akka
- SBT: how to modify it:test with a task that calls the original test task?
- With akka http, how can I inject request headers into an incoming route in the server?
- How to create new test report directory with timestamp every time I run a test and keep the old test reports using scalatest and sbt
- Get underlying Actor from ActorRef with the Akka Test Kit
- SparkML - Getting several metrics at the same time with RegressionEvaluator()
- Using a WebService with Akka Actors and the play framework
- When calling Await.Result with a time duration, how does it ignore the future?
More Query from same tag
- js.Function2, how to?
- Spark's Column.isin function does not take List
- scala, unable to prepend list
- Scala: Type-level programming parameterised by nested type value
- How Silhouette JWT token keeps valid in stateless mode?
- Checking a play current mode makes an error occur
- How to retrieve specific values from an array of string in RDD spark
- Issue with Kafka stream filtering
- Play+Scala suite test not found type PlaySpecification
- How to parse a JSON object (which is a list) into simple Scala class objects in scala?
- Understanding Scala Play Actions and Futures
- resolve an implicit then use the type stored in it to resolve a second implicit
- Access all case class values without reflection
- / to %2f convert back in Ajax Request
- 'result should have length 3': How does the ScalaTest DSL work?
- Issue with using wildcard parameter twice in a case class
- Clean exception handling in Scala
- How to merge RDD array
- Problems with scala regex extractor
- Scala: Why my function can't print a string parameter?
- Scala unexpectedly not being able to ascertain type for expanded function
- Populating Drop down with the values from database in play frame work
- mapdb how to persist cross restart
- Play & JSON: How to make scala code more concise
- How to convert map(key,struct) to map(key,caseclass) in spark scala dataframe
- How to convert a spark DataFrame with a Decimal to a Dataset with a BigDecimal of the same precision?
- SecureSocial not using extended classes in Play! 2.1 project inside SBT Multi-Project
- How to mix-in a trait to instance?
- How to provide additional parameter to implicit conversion
- How Scala distinguishes between unary operators and characters in variable name