I have created a statemachine that needs to run on a java driven PLC. I want to check/run the code at intervals of 250ms like i do now. the only problem is that in some states I have a delay implemented. So what I want is that that delay (for example 1s delay) finishes first and then the 250ms interval timer can continue again. how would you do this/how to interupt the 250 ms timer until code has finished executing?
public class demoClass{
public void main(){
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
switch (StateMachine()) { //statemachine determines logic between states
case s10_StandBy:
doSomething_1();
break;
case s20_NormalStartOrFlush:
doSomething_2();
break;
}
}
}, 0, 250);
}
public void doSomething_1(){
// for example a one second delay is implemented here
}
}
}
I would consider using ScheduledExecutorService
and rewrite your main method in this way:
public class demoClass{
public void main(){
Runnable task1 = () -> {
switch (StateMachine()) { //statemachine determines logic between states
case s10_StandBy:
doSomething_1();
break;
case s20_NormalStartOrFlush:
doSomething_2();
break;
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay(task1, 0, 250, TimeUnit.MILLISECONDS);
}
public void doSomething_1(){
// for example a one second delay is implemented here
}
}