Handling date and time events in Java

3

I want to make a small application that launches a JFrame at a certain time of day but I do not know how to handle events that can perform those actions. I am currently using a thread to verify every so often if that is the time at which the JFrame should be launched. Is there a better way to do it?

    
asked by Joshep Rodriguez 18.03.2016 в 00:43
source

1 answer

1

You can use the Timer and TimerTask API.

The warning:

public class FrameAdvisor {

    public final static int AD_HOUR = 13; // 13 horas o 1PM
    private Timer timer;

    public FrameAdvisor() {
        timer = new Timer();
        // comprobará cada hora
        timer.schedule(new FrameAdvisorTask(), 100000);
    }
}

The timer that will be running every 1 hour:

public FrameAdvisorTask extends TimerTask {

    @Override
    public void run() {
        FrameOffert offert;
        int hourOfDay;

        hourOfDay = DateUtil.getHourOfDay();
        if(FrameAdvisor.AD_HOUR == hourOfDay) {
            offert = new FrameOffert();
            offert.setVisible(true);
        }
    }
}

Utilitarian class:

public final class DateUtils {

    private DateFormat fmt = new SimpleDateFormat("HH:mm:ss");

    public static int getHourOfDay() {
        String strDate = fmt.format(new Date());
        String hour = strDate.subString(0, 2);
        return Integer.parseInt(hour);
    }

}
    
answered by 18.03.2016 в 01:14