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
764 views
in Technique[技术] by (71.8m points)

java - Swing timer persistence after main method finishes

I am trying to create a program to perform a simple task and produce an output every x seconds. I also want the program to run until I decide to manually close the program.

I have been attempting to implement this using a Swing timer, as I believe this is the best way. The problem is I'm not sure how to keep the program going once the main method has finished executing. So for example I have:

 static ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          try {
            //do stuff
        } catch (Exception e) {
            e.printStackTrace();
        }
          }
  };
public static void main(String[] args) throws Exception{
      Timer timer = new Timer(3000, taskPerformer);
      timer.start();
  }

which just finishes execution immediately. I can dodge the problem by putting the current thread of execution to sleep Thread.currentThread().sleep(..), but this feels like a botch job, and will be ultimately be finite in duration. I can also do while(true), but I believe this is bad practice.

My question is how to get the desired persistence behavior, and if there is a better way than using Swing timers.

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A Swing Timer will stay alive as long as the EDT is alive, usually this is done by having a Swing GUI present and visible (this creates a non-daemon thread that persists until the GUI exits). If you don't need a Swing GUI, then don't use a Swing Timer. Perhaps instead use a java.util.Timer, and don't exit the main method til you give the word (however you plan to do that).


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

...