Java Hour getDelayToNextHour(int amount, boolean skipNext)

Here you can find the source of getDelayToNextHour(int amount, boolean skipNext)

Description

This method could be named better, Here is what it does If you want to schedule a task every 2 hours, it is easier to track it if it happens at 2 am, 4 am, 6 am, 8 am ....

License

Open Source License

Parameter

Parameter Description
amount a parameter

Declaration

public static long getDelayToNextHour(int amount, boolean skipNext) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;

public class Main {
    /**//w  ww  .j  a v  a 2s  . c  o m
     * This method could be named better, Here is what it does
     * If you want to schedule a task every 2 hours, it is easier
     * to track it if it happens at 2 am, 4 am, 6 am, 8 am .... 
     * rather than 2 hours from the time it is triggered 
     *  
     *  If you want to skip the first run to make sure there is 
     *  a minimum delay of "amount" hours, set skipNext to true
     * 
     * @param amount
     * @return
     */
    public static long getDelayToNextHour(int amount, boolean skipNext) {
        if (amount <= 0 || amount > 12) {
            throw new IllegalArgumentException("The amount must be between 1 and 12 and be a divisor of 24");
        }
        Calendar c = Calendar.getInstance();
        long currentTime = c.getTimeInMillis();
        c.clear(Calendar.MINUTE);
        c.clear(Calendar.SECOND);
        c.clear(Calendar.MILLISECOND);

        int hour = c.get(Calendar.HOUR);
        int offset = amount - (hour % amount);
        if (skipNext) {
            offset += amount;
        }
        c.add(Calendar.HOUR, offset);
        return (c.getTimeInMillis() - currentTime);
    }
}

Related

  1. getCurrentHour()
  2. getCurrentHour()
  3. getCurrentHours()
  4. getCurrHour()
  5. getDelay(int hour, int min)
  6. getGMTHour(int localHour)
  7. getHexString(byte[] raw)
  8. getHour()
  9. getHour()