Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executorService.scheduleAtFixedRate to run task forever

I want a task to run forever after an interval of 1 min. TO accomplish that i wrote my task in

public void poll() {
    ScheduledExecutorService executorService= Executors.newScheduledThreadPool(1);
    ScheduledFuture files=executorService.scheduleAtFixedRate(new Runnable() {      
        @Override
        public void run() {
            String path="/Desktop/PNL/Test";
            List<String> filesPaths= new ArrayList<String>();
            File folder= new File(path);
            File[] listOfFiles= folder.listFiles();
            for (File file : listOfFiles) {
                filesPaths.add(file.getAbsolutePath());
            }
            if(!CollectionUtils.isEmpty(filesPaths)){
                try{
                    update(filesPaths);
                }
                catch(Exception e){
                    System.out.println(e.toString());
                }
            }
        }
    }, 0, 1, TimeUnit.MINUTES);
    files.cancel(false);
    //executorService.shutdown();

}

But the task executes only once and not after each minute. I don't understand whats wrong here.

like image 534
shruti rawat Avatar asked Sep 30 '15 07:09

shruti rawat


People also ask

What is the use of scheduledexecutorservice?

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.

What is the use of scheduleatfixedrate?

The scheduleAtFixedRate (TimerTask task, long delay, long period) is the method of Timer class. It is used to schedule the given task again and again in fixed rate of execution. It will begin after the specified delay. task: It is the task that is to be scheduled. delay: It is the time at which a task is executed, it is in the millisecond.

How to assign a task to an ExecutorService?

We can assign tasks to the ExecutorService using several methods including execute (), which is inherited from the Executor interface, and also submit (), invokeAny () and invokeAll (). The execute () method is void and doesn't give any possibility to get the result of a task's execution or to check the task's status (is it running):

How does The ExecutorService work?

With this approach, the ExecutorService will first stop taking new tasks and then wait up to a specified period of time for all tasks to be completed. If that time expires, the execution is stopped immediately. 5. The Future Interface


2 Answers

While executing your code, there was a NullPointerException caused at for (File file : listOfFiles) { which killed the thread.

The following change made it run continuously:

if (listOfFiles != null) {
    for (File file : listOfFiles) {
        filesPaths.add(file.getAbsolutePath());
    }
}

Moreover, files.cancel(false) ends the execution. Hence, had to comment this line. Reference of Future.cancel()

like image 135
James Jithin Avatar answered Sep 23 '22 12:09

James Jithin


Tested the code. As assumed by the others, the outcome is: Removing the line

files.cancel(false);

makes it run every minute. Else it runs only once.

Here is my code for test, which works:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class PeriodicCall {

public static void main(String args[]) {
    new PeriodicCall().poll();
}

public void poll() {
    System.out.println("poll"); // called once
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    ScheduledFuture<?> files = executorService.scheduleAtFixedRate(new Runnable() {      
        public void run() {
            System.out.println("running");
        }
    }, 0, 1, TimeUnit.MINUTES);
    //files.cancel(false);
    //executorService.shutdown();
}
}

My run() function contains only a System.out.println, so you should check your code inside your run() method. If it contains errors it will abort the whole execution.

like image 37
Andreas L. Avatar answered Sep 22 '22 12:09

Andreas L.