定时器无法正常工作(Java)

时间:2015-07-17 18:04:49

标签: java timer

我正在编写一个简单的Java代码,它使我能够将当前时间输出到单个文本文件中。我能够成功地将所有当前时间写入文本文件。但是,然后我尝试使用一个Timer,它每4秒触发一个简单的任务(输出当前时间),计时器无法正常工作。怎么可能呢?我该如何解决这个问题?谢谢!

代码:

      import java.io.BufferedWriter;
      import java.io.File;
      import java.io.FileWriter;
      import java.io.IOException;
      import java.io.Writer;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.Timer;
      import java.util.TimerTask;

      public class testWriteTimeToFile extends javax.swing.JFrame {

        public Writer writer=null;
        public File file;
        protected boolean isRunning=false;
        public Timer timer = new Timer();

        public testWriteTimeToFile() {
            initComponents();
            initTimer();
        }

        public void initTimer()
        {
          this.isRunning=true;  
          tryToGetUpdateTime();
        }

        public void tryToGetUpdateTime()
        {
            java.awt.EventQueue.invokeLater(new Runnable() {

            SimpleDateFormat sdfMonth = new SimpleDateFormat("dd/MM/yyyy");
            SimpleDateFormat sdfHour = new SimpleDateFormat("HH:mm:ss");

             public void run() {
                while (isRunning) {
                    TimerTask task = new TimerTask()
                    {
                        public void run()
                        {          
                            try{
                            file= new File("c:/Users/user/Desktop/updateTime.txt");

                            if(!file.exists())
                            {
                                file.createNewFile();
                            }

                            FileWriter fileWriter = new FileWriter(file,true);
                            BufferedWriter bufferWritter = new BufferedWriter(fileWriter);

                            Date date = new Date();  

                            bufferWritter.append(sdfMonth.format(date) + " " + sdfHour.format(date) + '\n');

                            bufferWritter.close();
                       }catch(IOException ex){
                           System.err.println("Error in Writer : " + ex);
                       }              
                  }
              };
                timer.scheduleAtFixedRate(task,0,4000); 
              }
             }
          });
        }

     public static void main(String args[]) {
     java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new testWriteTimeToFile().setVisible(true);
            }
        });
    }
}

2 个答案:

答案 0 :(得分:1)

您需要改进编码。 以下是您需要在代码中注意的事项

  • java name convention

  • 你在程序中有无限循环

  • 优良作法是从顶部导入包而不是 代码
  • 没有必要使用摇摆物。
  • 您需要学习如何使计时器工作。

尝试以下代码,我为你重新编写了

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class testWriteTimeToFile {

    public Writer writer = null;
    public File file;
    protected boolean isRunning = false;
    public Timer timer = null;

    public testWriteTimeToFile(int n) {
        // initComponents();
        initTimer();
        timer = new Timer();

        // run task every 4 seconds
        timer.schedule(new Task(1,2,3), 0, n * 1000);
    }

    public void initTimer() {
        this.isRunning = true;
        // tryToGetUpdateTime();
    }

    class Task extends TimerTask {

        private int a,b,c;      
        private double e,f,g;
        private String h,i,j;

        // take int
        public Task (int a, int b, int c){

            this.a = a;
            this.b = b;
            this.c = c;
        }

        // take double
        public Task (double e, double f, double g){

            this.e = e;
            this.f = f;
            this.g = g;
        }

        // take string
        public Task (String h, String i, String j){

            this.h = h;
            this.i = i;
            this.j = j;
        }

        @Override
        public void run() {
            final SimpleDateFormat sdfMonth = new SimpleDateFormat("dd/MM/yyyy");
            final SimpleDateFormat sdfHour = new SimpleDateFormat("HH:mm:ss");
            // only do it for 5 second
            file = new File("c:/test/time.txt");

            try {

                FileWriter fileWriter = new FileWriter(file, true);
                BufferedWriter bufferWritter = new BufferedWriter(fileWriter);

                Date date = new Date();

                bufferWritter.append(sdfMonth.format(date) + " "
                        + sdfHour.format(date) + '\n');

                bufferWritter.close();
            } catch (IOException ex) {
                System.err.println("Error in Writer : " + ex);
            }

        }

    }

    public static void main(String args[]) {

        new testWriteTimeToFile(4);

    }
}

答案 1 :(得分:0)

您的while循环会在每次迭代时不断调度新的TimerTask。 Timer工作正常,但你应该只安排一个TimerTask实例。