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?
public interface ScheduledExecutorService extends ExecutorService. An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution.
ScheduledExecutorService is an ExecutorService which can schedule tasks to run after a delay, or to execute repeatedly with a fixed interval of time in between each execution. Tasks are executed asynchronously by a worker thread, and not by the thread handing the task to the ScheduledExecutorService .
Learn to cancel a task submitted to an executor service if the task still has to be executed and/or has not been completed yet. We can use the cancel() method of Future object that allows making the cancellation requests.
ThreadPoolTaskScheduler ThreadPoolTaskScheduler is well suited for internal thread management, as it delegates tasks to the ScheduledExecutorService and implements the TaskExecutor interface – so that single instance of it is able to handle asynchronous potential executions as well as the @Scheduled annotation.
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.
I have been looking for a scala api for scheduled execution as well.
Java's ScheduledExecutor:
I wrote a little scala wrapper for the single task scheduling. See the gist: https://gist.github.com/platy/8f0e634c64d9fb54559c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With