Doubt when using TimerTask

2

Here is my example of using the TimerTask class and my problem is as follows:   I want to make this routine automatically every 12 hours. Currently nothing is happening, is something missing? And this class just give a tomcat deploy that works without instantiating it?

public class PausarTempo{

//INTERVALO DE TEMPO EM MILESEGUNDOS REFERENTE A 24 HORAS
public static final long TEMPO = (1000*60*60*20); 

public void pararTempo(){
//definindo a hora qua a tarefa sera executada pela primeira vez
   Calendar dataHoraInicio = Calendar.getInstance();
   dataHoraInicio.set(Calendar.HOUR_OFDAY,12); 
   dataHoraInicio.set(Calendar.MINUTE,0);
   dataHoraInicio.set(Calendar.SECOND,0);

Timer timer = null;
    if (timer == null) {
        timer = new Timer();
        TimerTask tarefa = new TimerTask() {
            @Override
            public void run() {
                try {
                    System.out.println("Començando...");
                   // MINHA REGRA
                    System.out.println("Fim.");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer.scheduleAtFixedRate(tarefa, dataHoraInicio.geteTime(), TEMPO);
}
}
    
asked by anonymous 04.01.2016 / 18:24

1 answer

2

It is necessary to make the first call of the method, after that, I believe that thread is running, waiting for the periods of time that has been set.

When testing with the main method, it works normally, I believe that this logic for the first delay did not work, because the delay also has to be in milisegundos . scheduleAtFixedRate(TimerTask task, long delay, long period)

So if you need the time at milliseconds of the Calendar API, call the method getTimeInMillis

public class PausarTempo {

    public static void main(String[] args) {
        pararTempo();
    }

    public static final long PERIODO_TEMPO = (1000 * 60 * 60 * 20);

    public static void pararTempo() {
        Timer timer = new Timer();
        TimerTask tarefa = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Començando...");
            }
        };
        timer.scheduleAtFixedRate(tarefa, 0, 5000); //Troque para PERIODO_TEMPO
    }
}

link

    
04.01.2016 / 18:54