Question

I'm have an intended task that is supposed to execute every 10 seconds. It works when I just run the project, meaning, it will run() once, but it will not the subsequent time. Can someone tell me which part is wrong..I spent hours trying to remedy this problem but to no avail :( This is my main:

public static void main(String[] args)  {

    launch(TestingApp.class, args);


    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new Cost(), 10*1000, 10*1000);}

This is the Cost code:

public class Cost extends TimerTask {

   public void run() {
      Calendar rightNow = Calendar.getInstance();
      Integer hour = rightNow.get(Calendar.HOUR_OF_DAY);

      if (hour == 3) {
         try {

            File file = new File("D:/TESTAPP/Testing.csv");
            if (file != null) {
               Opencsv csv = new Opencsv();

               csv.Csvreader();

            }
         } catch (IOException ex) {
            Logger.getLogger(Cost.class.getName()).log(Level.SEVERE, null, ex);
         }
      }

      else {

      }
   }
}

Some of the methods I tried was ending a thread.sleep to the end of Cost code, and the other method I tried was added a while(true) my main...

Was it helpful?

Solution

I suspect that this:

Opencsv csv = new Opencsv();
csv.Csvreader();

is blocking the timer's thread. Have you tried doing this in a background thread?

For example, your code is equivalent to this:

import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {
   public static void main(String[] args) {
      Timer timer = new Timer();
      timer.scheduleAtFixedRate(new TimerTask() {

         @Override
         public void run() {
           System.out.println("here");
           try {
              Thread.sleep(10 * 1000);
           } catch (InterruptedException e) {}
         }
      }, 1000, 1000);
   }
}

I'm suggesting that instead you do the inner stuff in a background thread so as not to slow the Timer down. Note the different times of execution of this:

import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {
   public static void main(String[] args) {
      Timer timer = new Timer();
      timer.scheduleAtFixedRate(new TimerTask() {

         @Override
         public void run() {
            new Thread(new Runnable() {
               public void run() {
                  System.out.println("here");
                  try {
                     Thread.sleep(10 * 1000);
                  } catch (InterruptedException e) {}
               }
            }).start();
         }
      }, 1000, 1000);
   }
}

Edit 2
Again, your question has a "swing" tag suggesting that your question involves code that is part of a Swing GUI. If so, then the recommendations may need to be different, especially if any of your code needs to be called on the Swing event thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top