Doubt when using Timertask

Asked

Viewed 585 times

2

follows my example of class use TimerTask and my problem is this: I want to make sure that every day the 12 hours is done this routine automatically. Currently nothing is happening, is this missing something? And this class just give a deploy on Tomcat 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);
}
}

1 answer

2


It is necessary to make the first call of the method, after that, I believe that it remains a thread running, waiting for the periods of time that was set.

When testing by the method main, works normally, I believe that this logic for the first delay, did not work, poís the delay also needs to be in milisegundos. scheduleAtFixedRate(TimerTask task, long delay, long period)

So if you need the time at milliseconds API Calendar, 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
    }
}

https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html

  • I understood Douglas, so to work I will have to activate the method only once. In relation to "getTime()" it worked well. I will test here in the production environment and activate the manual method and Jaja put if it worked, vlws.

  • In the production environment ta ok tbm. Closed topic vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.