Search code examples
javacounterscheduledexecutorservice

How to change value of period for scheduleAtFixedRate when program is running


I am writing distributed network of counters and I use scheduleAtFixedRate from ScheduledExecutorService class to send packets between computers in the network and print current value of counter on each computer when elapsed synPeriod. When I type the command "set period [value]", the period of scheduleAtFixedRate should be changed on the [value]. I update value of period variable, but it doesn't affect on period in scheduleAtFixedRate.. Is there any possibility to change the value when it works? Or any way is to stop the executor and then invoke it again with another period?

Runnable printer = () -> {
        try
        {
            //send packet with value of counter
            Thread.sleep(200);
        }
        catch (IOException e)
        {
        }
        catch (InterruptedException e)
        {
        }
        System.out.println("Counter value: " + counter);
    };
ScheduledExecutorService printerExecutor = Executors.newScheduledThreadPool(1);
    printerExecutor.scheduleAtFixedRate(printer, synPeriod, synPeriod, TimeUnit.SECONDS);

EDIT: I have read that ScheduledFuture would be useful and it works!.


Solution

  • You have to cancel the task an reschedule it with reqired value