Performing a specific task on a specific date and time

0

I'm trying to develop a small system that sends an email every Tuesday at 08:00 in the morning.

But I'm a bit confused, I can already send the email and check if it's Tuesday, but I do not know if it's correct.

The system keeps running, but since I'm still not checking to see if it's 08:00 in the morning, it should not send multiple emails without stopping, since the only condition for sending emails is to be Tuesday?

Here is the code:

public void gerarAviso() {
    Timer timer = null;
    if (timer == null) {
        timer = new Timer();
        Calendar data = Calendar.getInstance();
        TimerTask tarefa = new TimerTask() {
            @Override
            public void run() {
                System.err.println("DATA: " + data);
                if (data.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY){
                    System.out.println("É terça feira");
                    EnviaEmail e = new EnviaEmail();
                    e.enviaEmail("[email protected]");
                }else {
                        System.out.println("Não é terça feira!");
                }    
            }
        };
        timer.schedule(tarefa, data.getTime());
    }
}
    
asked by anonymous 08.09.2015 / 14:37

1 answer

1

The schedule (TimerTask task, ) method only performs the task once. I will recommend you to use the method: scheduleAtFixedRate (TimerTask task, Date firstTime, long period) for the method to be repeated day by day. Remember that the period is measured in milliseconds.

You can also loop manually by waiting for a day to check the day of the week and send the email.

Source: link

    
08.09.2015 / 15:09