Class Scheduler

java.lang.Object
com.scivicslab.pojoactor.core.scheduler.Scheduler
All Implemented Interfaces:
AutoCloseable

public class Scheduler extends Object implements AutoCloseable
A scheduler for periodic task execution with ActorRef.

This class provides scheduling capabilities for actors using lambda expressions. Tasks are executed on actors via ActorRef.ask(java.util.function.Function), ensuring thread-safe access to actor state.

Usage Example:


 ActorSystem system = new ActorSystem("my-system", 4);
 Scheduler scheduler = new Scheduler();

 ActorRef<MyActor> actorRef = system.actorOf("myActor", new MyActor());

 // Schedule a task to run every 10 seconds
 scheduler.scheduleAtFixedRate("health-check", actorRef,
     actor -> actor.checkHealth(),
     0, 10, TimeUnit.SECONDS);

 // Schedule with fixed delay (waits for completion before next run)
 scheduler.scheduleWithFixedDelay("cleanup", actorRef,
     actor -> actor.cleanup(),
     60, 300, TimeUnit.SECONDS);

 // Schedule a one-time task
 scheduler.scheduleOnce("init", actorRef,
     actor -> actor.initialize(),
     5, TimeUnit.SECONDS);

 // Cancel a task
 scheduler.cancelTask("health-check");

 // Cleanup
 scheduler.close();
 

For workflow-based scheduling with action names, use SchedulerIIAR instead.

Since:
2.11.0 (refactored from IIActorRef-based to ActorRef-based)
Author:
devteam@scivicslab.com
See Also:
  • Constructor Details

    • Scheduler

      public Scheduler()
      Constructs a new Scheduler with default thread pool size (2).
    • Scheduler

      public Scheduler(int poolSize)
      Constructs a new Scheduler with the specified thread pool size.
      Parameters:
      poolSize - the number of threads in the scheduler's thread pool
  • Method Details

    • scheduleAtFixedRate

      public <T> String scheduleAtFixedRate(String taskId, ActorRef<T> actorRef, Consumer<T> action, long initialDelay, long period, TimeUnit unit)
      Schedules a task to execute periodically at a fixed rate.

      The task is executed on the target actor via ActorRef.ask(), ensuring thread-safe access to the actor's state.

      Fixed Rate vs Fixed Delay:

      With scheduleAtFixedRate, executions are scheduled to start at regular intervals (0, period, 2*period, 3*period, ...) regardless of how long each execution takes. If an execution takes longer than the period, the next execution starts immediately after the previous one completes (no delay accumulation).

      Use this method when you need consistent timing intervals, such as metrics collection or heartbeat checks at precise intervals.

      In contrast, scheduleWithFixedDelay(java.lang.String, com.scivicslab.pojoactor.core.ActorRef<T>, java.util.function.Consumer<T>, long, long, java.util.concurrent.TimeUnit) waits for a fixed delay after each execution completes before starting the next one.

       scheduleAtFixedRate (period=100ms, task takes 30ms):
       |task|          |task|          |task|
       0    30   100   130   200   230   300ms
            └─period─┘      └─period─┘
       
      Type Parameters:
      T - the type of the actor
      Parameters:
      taskId - unique identifier for this scheduled task
      actorRef - reference to the target actor
      action - the action to perform on the actor
      initialDelay - delay before first execution
      period - interval between successive execution starts
      unit - time unit for the delays
      Returns:
      the taskId for reference
      See Also:
    • scheduleWithFixedDelay

      public <T> String scheduleWithFixedDelay(String taskId, ActorRef<T> actorRef, Consumer<T> action, long initialDelay, long delay, TimeUnit unit)
      Schedules a task to execute periodically with a fixed delay between executions.

      The task is executed on the target actor via ActorRef.ask(), ensuring thread-safe access to the actor's state.

      Fixed Delay vs Fixed Rate:

      With scheduleWithFixedDelay, the delay between the termination of one execution and the start of the next is always delay time units. This ensures that executions never overlap and there is always a guaranteed rest period between executions.

      Use this method when you need to ensure a minimum gap between executions, such as polling operations where you want to avoid overwhelming a resource, or when each execution depends on external state that needs time to stabilize.

      In contrast, scheduleAtFixedRate(java.lang.String, com.scivicslab.pojoactor.core.ActorRef<T>, java.util.function.Consumer<T>, long, long, java.util.concurrent.TimeUnit) schedules executions at fixed intervals regardless of execution duration.

       scheduleWithFixedDelay (delay=100ms, task takes 30ms):
       |task|              |task|              |task|
       0    30        130  160        260  290ms
            └──delay──┘    └──delay──┘
       
      Type Parameters:
      T - the type of the actor
      Parameters:
      taskId - unique identifier for this scheduled task
      actorRef - reference to the target actor
      action - the action to perform on the actor
      initialDelay - delay before first execution
      delay - delay between termination of one execution and start of next
      unit - time unit for the delays
      Returns:
      the taskId for reference
      See Also:
    • scheduleOnce

      public <T> String scheduleOnce(String taskId, ActorRef<T> actorRef, Consumer<T> action, long delay, TimeUnit unit)
      Schedules a task to execute once after a specified delay.

      The task will be executed once after the specified delay and then automatically removed from the scheduled tasks.

      Type Parameters:
      T - the type of the actor
      Parameters:
      taskId - unique identifier for this scheduled task
      actorRef - reference to the target actor
      action - the action to perform on the actor
      delay - delay before execution
      unit - time unit for the delay
      Returns:
      the taskId for reference
    • cancelTask

      public boolean cancelTask(String taskId)
      Cancels a scheduled task.

      If the task is currently executing, it will be allowed to complete. The task will not be executed again after cancellation.

      Parameters:
      taskId - identifier of the task to cancel
      Returns:
      true if the task was found and cancelled, false otherwise
    • getScheduledTaskCount

      public int getScheduledTaskCount()
      Returns the number of currently scheduled tasks.
      Returns:
      the number of active scheduled tasks
    • isScheduled

      public boolean isScheduled(String taskId)
      Checks if a task with the given ID is currently scheduled.
      Parameters:
      taskId - the task identifier to check
      Returns:
      true if the task exists and is not cancelled, false otherwise
    • close

      public void close()
      Shuts down the scheduler and cancels all scheduled tasks.

      This method will attempt to gracefully shutdown the scheduler executor, waiting up to 5 seconds for tasks to terminate.

      Specified by:
      close in interface AutoCloseable