Class TaskManager

java.lang.Object
com.ultikits.ultitools.manager.TaskManager

@Internal public class TaskManager extends Object
Manages scheduled tasks for plugin modules.

Scans beans for Scheduled methods and runs them on their owner's scheduler. Module registration, reload and the diagnostic task counts are main-thread confined; the scheduler engine itself supports concurrent submission and retirement.

Config-bound tasks (#531): a Scheduled method whose period or delay is bound to a module config key is scheduled from the key's value (seconds, times 20) and kept as a TaskManager.BoundTask handle in boundTasks, so rescheduleBound(UltiToolsPlugin) can find that one method's task again after /ul reload. A method with no binding takes the literal scheduling path, with the same timing values and log line.

Since:
6.2.0
  • Field Details

  • Constructor Details

    • TaskManager

      public TaskManager(org.bukkit.plugin.java.JavaPlugin hostPlugin)
    • TaskManager

      TaskManager(PaperSchedulerEngine engine)
  • Method Details

    • schedulerFor

      public Scheduler schedulerFor(UltiToolsPlugin plugin)
      Returns this module instance's owner, independent of any same-name replacement. Must be called on the main thread, like module registration and unload.
      Parameters:
      plugin - the owning module instance
      Returns:
      the module's scheduler
      Throws:
      RejectedExecutionException - if this module instance was already retired
    • wasRetired

      private boolean wasRetired(UltiToolsPlugin plugin)
    • record

      private void record(Scheduler scheduler, TaskHandle task)
    • registerScheduledMethods

      public void registerScheduledMethods(UltiToolsPlugin plugin, Object bean)
      Scan a bean for Scheduled methods and register them on the owning scheduler.
      Parameters:
      plugin - the owning plugin module
      bean - the bean instance to scan
    • registerScheduledMethodsCore

      public void registerScheduledMethodsCore(Object bean)
      Scan a framework-owned object for Scheduled methods and register them.

      The other two entry points key their tasks on a plugin module or an external plugin, and both are reached by iterating a SimpleContainer's beans. An object the framework constructs directly -- PlayerCacheManager, for instance -- belongs to no container and is therefore reached by neither, which is why its @Scheduled method silently never ran before 6.3.0 (#384). This is the third bucket, for objects the framework owns.

      Callers must not invoke this ad hoc. The set of framework-owned types whose scheduled methods are registered is declared by PluginManager.FRAMEWORK_SCHEDULED_OWNER_TYPES and enforced by FrameworkScheduledWiringTest; adding an object here without adding its type there would reintroduce exactly the drift that guard exists to prevent.

      Parameters:
      bean - the framework-owned instance to scan
      Since:
      6.3.0
    • cancelAllCore

      public void cancelAllCore()
      Cancel every framework-owned scheduled task.

      Called from PluginManager.close(), which UltiTools.onDisable() invokes. A repeating task that is not cancelled here survives a /reload and a second copy is scheduled on the next enable.

      Since:
      6.3.0
    • scanAndSchedule

      private void scanAndSchedule(UltiToolsPlugin module, Object bean, Scheduler scheduler, Consumer<TaskHandle> recorder)
      Scan one bean for Scheduled methods and schedule each valid one, recording each task in its owning bucket as soon as it is created rather than batching them into a list returned at the end.

      The single implementation behind all three registration entry points, which differ only in which bucket (recorder) they file the resulting tasks under. Three copies of this body would be three places to keep a signature check, a scheduling rule or a log line in step.

      #410: before this, tasks were accumulated in a local list and handed to the owning bucket only via created.addAll(...) in the CALLER, after this method returned. If scheduling a later Scheduled method threw (e.g. runTaskTimer throwing because the host plugin became disabled mid-registration), every task already scheduled for earlier methods in this same scan was already a live Bukkit task, but the exception meant this method never returned, so created never reached any bucket -- cancelAll/cancelAllExternal/cancelAllCore had no record of them and could never cancel them at teardown. Calling recorder inside the loop, immediately after each task is scheduled, means an exception from a later method can no longer un-record an earlier one: whatever the loop reached before throwing is already exactly where it needs to be for teardown to find it. This also restores the original, pre-three-bucket-split behaviour of recording each task as it was scheduled, one at a time. #531: a config-bound method is handed to scheduleBound(UltiToolsPlugin, Object, Class, Method, Scheduled, Scheduler) instead and recorded in boundTasks as soon as it is scheduled, by the same #410 rule. Only a module has a config registry to bind against, so a bound method reached with no module (an external plugin's or a framework-owned bean) is refused.

      Parameters:
      module - the owning module, or null for an external plugin or the framework
      bean - the instance to scan
      scheduler - the instance-bound owner to submit to
      recorder - invoked once per successfully scheduled task, in declaration order, with that task -- files it into this bean's owning bucket immediately
      Throws:
      PluginModuleException - for a config-bound method with no module, or for a binding that cannot be resolved
      Since:
      6.3.0
    • cancelAll

      public void cancelAll(UltiToolsPlugin plugin)
      Cancel all scheduled tasks for a plugin.
      Parameters:
      plugin - the plugin to cancel tasks for
    • scheduleBound

      private void scheduleBound(UltiToolsPlugin module, Object bean, Class<?> targetClass, Method method, Scheduled scheduled, Scheduler scheduler)
      Schedules one config-bound Scheduled method from its resolved binding and records its handle in boundTasks immediately (#410).
      Throws:
      PluginModuleException - if the binding cannot be resolved
      ConfigurationException - if a bound value is out of range
    • arm

      private TaskHandle arm(TaskManager.BoundTask handle, long firstDelay)
      Schedules handle's method with its current timing, first running after firstDelay ticks. The trigger always runs on the main thread, where the reload step also runs. An async binding records that observed fire before handing only its method body to an async worker, one heartbeat later (#535).
    • dispatchAsync

      private void dispatchAsync(TaskManager.BoundTask handle)
      Dispatches a due body without letting worker start/completion change the trigger's phase.
    • invokeBound

      private static void invokeBound(TaskManager.BoundTask handle)
    • rescheduleBound

      public void rescheduleBound(UltiToolsPlugin plugin)
      Applies plugin's reloaded configuration to its config-bound Scheduled tasks. Called by UltiToolsPlugin.reloadSelf(), through PluginManager.applyReloadedConfigBindings, only after the configuration reload succeeded.

      For each bound task whose bound value changed:

      • it has run before: the next run is last run + new period, or the next tick if that moment has already passed;
      • it has not run yet: the first run is arm tick + new delay, or the next tick if that moment has already passed.
      So a reload never runs a task early and never postpones it by restarting its clock -- a 30-minute interest payment is neither paid on reload nor pushed back by repeated reloads. A task whose bound values did not change is left alone. A bound value that is now out of range (< 1 second, null, or too large) is not applied: the running value is kept and one WARNING names the module, the key, the rejected value and the value kept.

      Where "the last run" comes from. Every bound task's trigger is sync, and its last fire is observed at the moment the trigger starts -- the same thread this step runs on, so the two cannot race. For an async binding, worker start and completion do not affect this stamp. Reload cancels only the trigger, leaving already-dispatched work alone (#535). No server dispatch time or boot-time scheduler clock is predicted.

      Must run on the main thread, where TaskManager's collections live; from any other thread it throws before reading them (PluginManager checks first and logs instead).

      Parameters:
      plugin - the module whose configuration was just reloaded
      Since:
      6.3.0
    • rescheduleBound

      public void rescheduleBound(UltiToolsPlugin plugin, ReloadReport report)
      rescheduleBound(UltiToolsPlugin), also recording in report one partial reason per bound value kept in place of a refused one (#595), so the module's reload is not reported as complete while a task kept its old timing.
      Parameters:
      plugin - the module whose configuration was just reloaded
      report - the module's reload report
      Since:
      6.3.0
    • rescheduleOne

      private void rescheduleOne(UltiToolsPlugin plugin, TaskManager.BoundTask handle, ReloadReport report)
    • reloadedTicks

      private static long reloadedTicks(UltiToolsPlugin plugin, TaskManager.BoundTask handle, ConfigBindings.Source source, long currentTicks, Set<String> warnedKeys, ReloadReport report)
      Returns:
      the reloaded value of source in ticks, or currentTicks if it is unbound or its new value is out of range (then warned and reported once per key)
    • validateConfigBindings

      static void validateConfigBindings(UltiToolsPlugin module, Object bean)
      Load-time check of every config-bound Scheduled method on bean, over exactly the methods scanAndSchedule(UltiToolsPlugin, Object, Scheduler, Consumer) would schedule. Used by PluginManager before any Bukkit side effect, so an invalid binding refuses the one module (#531).
      Parameters:
      module - the module being assembled
      bean - one of its container singletons
      Throws:
      PluginModuleException - if a binding cannot be resolved
      ConfigurationException - if a bound value is out of range
      Since:
      6.3.0
    • firstBoundMethod

      static String firstBoundMethod(Object bean)
      Parameters:
      bean - a container singleton
      Returns:
      Class.method of the first config-bound Scheduled method that scanAndSchedule(UltiToolsPlugin, Object, Scheduler, Consumer) would schedule, or null
      Since:
      6.3.0
    • refuseConfigBindings

      static void refuseConfigBindings(Object bean)
      Refuses any config-bound Scheduled method on bean -- for a container with no module config registry (an external plugin's).
      Parameters:
      bean - one of the container's singletons
      Throws:
      PluginModuleException - naming the first bound method found
      Since:
      6.3.0
    • checkSignatureOrWarn

      private static boolean checkSignatureOrWarn(Class<?> targetClass, Method method)
      The two signature rules scanAndSchedule(UltiToolsPlugin, Object, Scheduler, Consumer) skips a method for, each logging the same WARNING it always has.
      Returns:
      true if method takes no parameters and returns void
    • isSchedulableSignature

      private static boolean isSchedulableSignature(Method method)
      The two signature rules scanAndSchedule(UltiToolsPlugin, Object, Scheduler, Consumer) skips a method for, without its logging.
    • bindingOutsideModule

      private static PluginModuleException bindingOutsideModule(Class<?> targetClass, Method method)
    • getTargetClass

      private Class<?> getTargetClass(Class<?> clazz)
      Get the original class, unwrapping proxies generated by ProxyFactory.

      Delegates entirely to ProxyFactory.unwrap(Class) - proxy identity is owned by that class, not derived here. A proxy of a proxy already carries a ProxyOf marker naming the original target, so this needs no hierarchy walk and no Object.class fallback: unwrap returns a non-proxy argument unchanged, which is the same answer the removed fallback was approximating for the common case.

    • registerScheduledMethodsExternal

      public void registerScheduledMethodsExternal(String pluginName, Object bean)
      Scan a bean for Scheduled methods and register them for an external plugin.
      Parameters:
      pluginName - the external plugin name (used as key)
      bean - the bean instance to scan
      Since:
      6.2.2
    • cancelAllExternal

      public void cancelAllExternal(String pluginName)
      Cancel all scheduled tasks for an external plugin.
      Parameters:
      pluginName - the external plugin name
      Since:
      6.2.2
    • getTaskCount

      int getTaskCount(UltiToolsPlugin plugin)
      Get the number of registered tasks for a plugin (for testing).
    • getCoreTaskCount

      int getCoreTaskCount()
      Get the number of registered framework-owned tasks (for testing).
      Since:
      6.3.0
    • getExternalTaskCount

      int getExternalTaskCount(String pluginName)
      Get the number of registered tasks for an external plugin (for testing).
    • taskCount

      private int taskCount(Scheduler scheduler)