简体   繁体   English

计时器无法正常运行(Java)

[英]Timer is not working properly (Java)

I am writing a simple Java code which enable me to output current time into a single text file. 我正在编写一个简单的Java代码,使我能够将当前时间输出到单个文本文件中。 I was able to write all the current time into text file successfully. 我能够将当前所有时间成功写入文本文件。 However, then I tries to use a Timer which trigger a simple task (output the current time) in every 4 seconds, the timer is not working properly. 但是,然后我尝试使用一个计时器,该计时器每4秒触发一次简单任务(输出当前时间),该计时器无法正常工作。 How could this possible? 这怎么可能呢? How can I fix this problem? 我该如何解决这个问题? Thanks ! 谢谢 !

Code: 码:

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

You need improve your coding. 您需要改善编码。 Here are the things you need to pay attention in your code 这是您在代码中需要注意的事情

  • java name convention Java名称约定

  • you have infinite loop in the program 你在程序中有无限循环

  • It is good practice that import the package from the top not in the code 优良作法是从代码顶部而不是代码顶部导入包
  • There is no need to use swing stuff. 无需使用摇摆物品。
  • You need learn how to make timer work. 您需要学习如何使计时器工作。

Try the following code, I rewrote it for you 尝试以下代码,我为您重写了

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);

    }
}

Your while loop continually schedules a new TimerTask every iteration. 您的while循环会在每次迭代时连续调度一个新的TimerTask。 The Timer is working fine, but you should only schedule a single TimerTask instance. Timer工作正常,但您仅应安排一个TimerTask实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM