Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduled Executor in Scala

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?

like image 510
Michael Avatar asked May 18 '13 14:05

Michael


People also ask

What is scheduled executor service?

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.

How ScheduledExecutorService works?

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 .

How do I stop scheduled executor service?

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.

What is ThreadPoolTaskScheduler?

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.


2 Answers

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.

like image 166
Marius Danila Avatar answered Sep 20 '22 18:09

Marius Danila


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

like image 28
MikeB Avatar answered Sep 19 '22 18:09

MikeB