1

It's the first time I use Java for a project and I need to do this:

  • send a CoAP POST request to turn on an actuator
  • wait 10 seconds
  • send a CoAP POST request to turn off the actuator.

    I'm using this code inside the method I wrote that has to automatically turn on/off the actuator:
new java.util.Timer().schedule(
    new java.util.TimerTask() {
        @Override
            public void run (){
                Request postRequest2 = new Request(CoAP.Code.POST);
                postRequest2.setURI(String.format("%s%s", COAP_ENDPOINT1, targetStatusActuatorUri));
                postRequest2.setConfirmable(true);
            }
    },
    10000
);

But it throws an error Unreachable statement and I don't understand why.

Mo0oon9898
  • 11
  • 2
  • 2
    Welcome to StackOverflow! When you say "it throws an error" do you mean that it fails to compile? "Unreachable statement" sounds like a compilation error to me. If so, which line of code does the compiler error refer to? Please update your question with that information if you can. – Sam Jan 29 '22 at 15:48
  • 1
    Please be respectful to your readers when posting here. Do not be lazy with your typing such as ignoring proper use of uppercase. This site is meant to be more like Wikipedia, less like a casual chat room. Omit needless chit-chat, including pleas for help. I fixed some of these problems for you this time. – Basil Bourque Jan 29 '22 at 16:56

1 Answers1

2

As commented, you need to supply more debugging details.

ScheduledExecutorService

More generally, I can say that Timer and TimerTask classes were years ago supplanted by the Executors framework. Their Javadoc so notes.

A ScheduledExecutorService allows you to specify a delay before executing your task. Establish the service, and keep it around for later use.

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;

Define your task as a Runnable (or Callable).

Runnable task = () -> {
    turnOffActuator() ;
};

In your business logic, turn on the actuator, then assign the turning-off task to the executor while scheduling with a delay.

turnOnActuator() ;
ses.schedule( task , 10 , TimeUnit.SECONDS ) ;

Be sure to eventually shut down your executor service before your app ends/exits. Otherwise the pool of threads backing your executor service may continue running indefinitely, like a zombie ‍♂️.

All of this has been covered many times already on Stack Overflow. Search to learn more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154