Tutorial :Is there a Scala-specific way to implement periodic execution?



Question:

AKA doing something at set intervals.

For example, let's say I want to scan a certain directory every 60 seconds.

In Java, I would use a ScheduledExecutorService like so:

Executor pool = Executors.newScheduledThreadPool(10)  pool.scheduleAtFixedRate(scanner, 0, 60, TimeUnit.SECONDS)  

and that works fine.

The thing is, I'm thinking I'd like to try using Scala actors in my program, but I'm a little confused as to how to combine actors and Java Executors, or whether they should be.

I guess maybe I could have a simple runner which would merely send a message to an actor every N seconds -- does that make sense?


Solution:1

I guess maybe I could have a simple runner which would merely send a message to an actor every N seconds -- does that make sense?

Yes, and consider using Akka for the Actors by the way. It has a simpler API, better performance and has a lot of yummy stuff in it.


Solution:2

You could try the Scala Executor itself, instead of the Java one.

An object that executes submitted java.lang.Runnable tasks.
This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.
An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:

 Executor executor = anExecutor;   executor.execute(new RunnableTask1());   executor.execute(new RunnableTask2());   ...  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »