Search code examples
javatimertimertask

Make scheduleAtFixedRate accept hours instead of ms?


How do I make scheduleAtFixedRate accept the argument in hours rather than ms, as it does below? The program should run at regular 1 hour intervals i.e. 11:25:00:00, 12:25:00:00, and so on.

public class Kronos {
        public static void main(String[] args) throws ParseException {
            DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = dateFormatter.parse("2017-02-09 11:25:00");

            long hours = 1;
            long msPerHour = 3600000;
            long period = hours * msPerHour;

            Timer timer = new Timer();
            TimerTask taskNew = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("ALL WORK AND NO PLAY MAKES JACK A DULL BOY");
                }
            };

            taskNew.scheduledExecutionTime();
            timer.scheduleAtFixedRate(taskNew, d, period);
        }
    }

Initially I considered something like TimeFormat.HOURS but I don't know how to implement it...


Solution

  • TimeUnit.HOURS.toMillis(hours) is a concise way of converting hours to milliseconds. The method in question does not seem capable of accepting anything other than milliseconds.