Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute list of runnables with time gap

I have a problem to solve. in which i need to run list of runnable objects with some delay in each request execution.

Say for ex I have a list like below

List<MyReqObject> myReqObjects=new ArrayList<MyReqObject>();

and I have created an executor with X number of threads like below

ExecutorService execute=Executors.newFixedThreadPool(X)

now using execute.invokeAl(myReqObjects); i an trying to invoke all these requests...

but I should have a delay in between these. to achieve this I tried

ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(myObject, 2, 7, SECONDS); 

but here I cannot send list as a argument so I can execute same request for 7 sec with delay of 2 sec...

so is there a way to solve my problem please suggest me

like image 599
user1632316 Avatar asked Mar 14 '13 05:03

user1632316


People also ask

What is running and runnable?

In the nomenclature of most operating systems, "running" means that the thread actually is executing instructions on some CPU, and "runnable" means that nothing prevents the thread from "running" except the availability of a CPU to run on. A Java program can not tell the difference between those two states.

What is ThreadPool Executor?

ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.

What is difference between runnable and thread in Java?

Runnable is an interface which represents a task that could be executed by either a Thread or Executor or some similar means. On the other hand, Thread is a class which creates a new thread. Implementing the Runnable interface doesn't create a new thread. Java Docs clearly explains the difference between them.

How thread Executor Works?

The executor service creates and maintains a reusable pool of threads for executing submitted tasks. The service also manages a queue, which is used when there are more tasks than the number of threads in the pool and there is a need to queue up tasks until there is a free thread available to execute the task.


1 Answers

create a Timer:

Timer timer = new Timer();

if you need to run it once then:

timer.schedule(new TimerTask() {
   @Override
   public void run() {
   // Your code here
   }
}, 2*1000); 

to run repeatedly:

 timer.scheduleAtFixedRate(new TimerTask() {
   @Override
   public void run() {
   // Your code here
   }
}, 2*1000); 

see some coding examples for Timer and TimerTask here

like image 77
aviad Avatar answered Oct 04 '22 22:10

aviad