Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

java - How to interupt a timer until code is finished executing

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
    }
    
    }
}
question from:https://stackoverflow.com/questions/65886715/how-to-interupt-a-timer-until-code-is-finished-executing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...