5

I would like to use ScheduledExecutorService to export some data in scheduled manner.

In my code below I have called 2 different task in 2 different time intervals. There will be a chance where multiple task is schedule in 1 ScheduledExecutorService when user creates multiple scheduling to export multiple data(different reports).

  1. Is it safe to use single ScheduledExecutorService to run more than one task?

  2. Is it possible to stop one of the task(Eg. service.scheduleAtFixedRate(runnable2, 0, 10, TimeUnit.SECONDS);) if user deletes specific scheduling?

    public static void main(String... args) {        
          Runnable runnable = new Runnable() {          public void run() {
        // task to run goes here
          System.out.println("Every 5 sec: "+ new java.util.Date());
    
      }
    };
    
    Runnable runnable2 = new Runnable() {
          public void run() {
            // task to run goes here
              System.out.println("Every 10 sec: "+ new java.util.Date());
          }
        };
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS);
    service.scheduleAtFixedRate(runnable2, 0, 10, TimeUnit.SECONDS);
    }
    
  • This works even with one thread, but you can start as many threads as there are task to improve timing. – Marko Topolnik Nov 22 '16 at 09:06
  • @MarkoTopolnik- Thanks. Will I be able to stop one of the task if I use this method of scheduling? – Nithish Vijayan Nov 22 '16 at 09:12
  • that can be really trouble , you might have to create custom `Runnable` in order to manually interrupt them. check [this answer](http://stackoverflow.com/questions/1418033/java-executors-how-can-i-stop-submitted-tasks) , it refers to a callable , but you would do it in the same way as you are keeping the references to the `runnable`s instead of the `Future` – AntJavaDev Nov 22 '16 at 09:29
  • Thanks @AntJavaDev..Got better understanding after viewing the post you have mentioned – Nithish Vijayan Nov 22 '16 at 09:39
  • You will have no trouble canceling an individual schedule, if that's what you asked. – Marko Topolnik Nov 22 '16 at 10:01

0 Answers0