如何在代码执行完毕之前中断定时器

How to interupt a timer until code is finished executing

我创建了一个需要在 java 驱动的 PLC 上 运行 的状态机。我想像现在一样以 250 毫秒的间隔 check/run 代码。唯一的问题是在某些州我实施了延迟。 所以我想要的是该延迟(例如 1s 延迟)首先完成,然后 250ms 间隔计时器可以再次继续。你会如何this/how 中断 250 毫秒计时器直到代码执行完毕?

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
    }
    
    }
}

我会考虑使用 ScheduledExecutorService 并以这种方式重写您的主要方法:

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
    }
}