Dennis QT
Dennis QT

Reputation: 125

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

Upvotes: 0

Views: 824

Answers (2)

Jegg
Jegg

Reputation: 549

You need improve your coding. Here are the things you need to pay attention in your code

  • java name convention

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

    }
}

Upvotes: 1

Bradley M Handy
Bradley M Handy

Reputation: 613

Your while loop continually schedules a new TimerTask every iteration. The Timer is working fine, but you should only schedule a single TimerTask instance.

Upvotes: 0

Related Questions