Class Timer

java.lang.Object
com.framed.core.utils.Timer

public class Timer extends Object
A utility class for scheduling tasks with delays or at fixed intervals using a ScheduledExecutorService.

This class provides instance-level scheduling, meaning each Timer object manages its own executor. This avoids global state issues and allows independent lifecycle management for different components.

Features:

  • Schedule a one-time task after a specified delay.
  • Schedule a periodic task at a fixed interval.
  • Shutdown the scheduler when no longer needed to free resources.

Example usage:


 Timer timer = new Timer();
 timer.setTimer(1000, () -> System.out.println("Executed after 1 second"));
 timer.setPeriodic(5000, () -> System.out.println("Executed every 5 seconds"));

 // Later, when done:
 timer.shutdown();
 

Note: Always call shutdown() when the timer is no longer needed to prevent resource leaks.

  • Field Details

  • Constructor Details

    • Timer

      public Timer()
  • Method Details

    • setTimer

      public void setTimer(long delayMillis, Runnable task)
      Schedules a one-time task to execute after the specified delay.
      Parameters:
      delayMillis - the delay in milliseconds before executing the task
      task - the Runnable task to execute
    • setPeriodic

      public void setPeriodic(long intervalMillis, Runnable task)
      Schedules a periodic task to execute at a fixed interval.
      Parameters:
      intervalMillis - the interval in milliseconds between consecutive executions
      task - the Runnable task to execute periodically
    • shutdown

      public void shutdown()
      Shuts down the scheduler and stops accepting new tasks.

      Pending tasks will still execute unless ExecutorService.shutdownNow() is used.