Class IntervalChecker

java.lang.Object
de.arstwo.twotil.IntervalChecker

public class IntervalChecker extends Object
A utility class designed for managing and checking time intervals in a thread-safe manner.

This class simplifies the boilerplate code necessary to handle interval checking.

Usage example:


   IntervalChecker everyMinute = IntervalChecker.every(1, ChronoUnit.MINUTES);
   if (everyMinute.updateIfDue()) {
     // Do the task...
   }
   // alternatively:
   everyMinute.executeIfDue(myTask::run);
 
 
  • Method Details

    • every

      public static IntervalChecker every(long amount, TemporalUnit unit)
      Creates a new IntervalChecker with the specified time interval. The returned timer is marked as "due".
      Parameters:
      amount - The amount of the specified unit.
      unit - The time unit, usually ChronoUnit.
      Returns:
      An IntervalChecker set to the specified time interval.
      See Also:
    • updateIfDue

      public boolean updateIfDue()
      Checks the interval and atomically resets the timer if the time has expired.
      Returns:
      true if the time had expired, otherwise false.
    • executeIfDue

      public boolean executeIfDue(Runnable task)
      Executes the specified operation if the interval has expired. In that case, also resets the timer.
      Parameters:
      task - The task to be performed.
      Returns:
      true if the interval had expired, otherwise false.
    • forceChecked

      public void forceChecked()
      Forces a new time interval. Typically when the task has been completed externally.
    • forceDue

      public void forceDue()
      Forces the timer to indicate that the interval time has expired at the next check.