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 Summary

    Fields
    Modifier and Type
    Field
    Description
    static final DateTimeFormatter
    Shared formatter for timestamps in the pattern yyyy-MM-dd'T'HH:mm:ss.SSSSSS (ISO-like, microsecond precision), used across the framework for serializing and parsing datapoint timestamps.
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    setPeriodic(long intervalMillis, Runnable task)
    Schedules a periodic task to execute at a fixed interval.
    void
    setTimer(long delayMillis, Runnable task)
    Schedules a one-time task to execute after the specified delay.
    void
    Shuts down the scheduler and stops accepting new tasks.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • formatter

      public static final DateTimeFormatter formatter
      Shared formatter for timestamps in the pattern yyyy-MM-dd'T'HH:mm:ss.SSSSSS (ISO-like, microsecond precision), used across the framework for serializing and parsing datapoint timestamps.
  • 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.