Scheduled Executor in Scala

2019-01-22 21:28发布

问题:

In Java I can use Scheduled Executor to schedule tasks to run after a given delay. I can use it in Scala but I wonder if there is a Scala API for that.

Is there any Scala API (as opposed to Scheduled Executor in Java) to schedule tasks?

回答1:

Akka has something similar with schedulers:

http://doc.akka.io/api/akka/2.1.4/#akka.actor.Scheduler

You can obtain one from the actor system:

val actorSystem = ActorSystem()
val scheduler = actorSystem.scheduler
val task = new Runnable { def run() { log.info("Hello") } }
implicit val executor = actorSystem.dispatcher

scheduler.schedule(
  initialDelay = Duration(5, TimeUnit.SECONDS),
  interval = Duration(10, TimeUnit.SECONDS),
  runnable = task)

If you are using Akka or something based on it, like Play, that would be the way to go.



回答2:

Previously, a duplicate question resulted in this toy.

scala> implicit class Expiry(val d: Deadline) extends AnyVal {
     | def expiring(f: =>Unit) =
     | future(Await.ready(Promise().future, d.timeLeft)) onComplete (_ => f)
     | }
defined class Expiry

scala> val x = new SyncVar[Boolean]()
x: scala.concurrent.SyncVar[Boolean] = scala.concurrent.SyncVar@597d9abe

scala> 10 seconds fromNow expiring {
     | println("That's all, folks.")
     | x.put(true)
     |     }

scala> x.take() 
That's all, folks.
res1: Boolean = true


回答3:

I have been looking for a scala api for scheduled execution as well.

Java's ScheduledExecutor:

  • uses a thread pool for running the scheduler and operating the timeouts, and so does not require a Thread per timeout
  • No akka needed

I wrote a little scala wrapper for the single task scheduling. See the gist: https://gist.github.com/platy/8f0e634c64d9fb54559c



回答4:

You can use scalaz's Task,

import scala.concurrent.duration.{FiniteDuration, SECONDS}
import scalaz.concurrent.Task
Task.schedule(Console.println("time's up"), FiniteDuration(5, SECONDS)).runAsync { _ => }