Class Script

  • All Implemented Interfaces:
    Scriptable

    public abstract class Script
    extends java.lang.Object
    implements Scriptable
    • Constructor Summary

      Constructors 
      Constructor Description
      Script()  
    • Method Summary

      All Methods Instance Methods Abstract Methods Concrete Methods 
      Modifier and Type Method Description
      abstract int loop()
      Executes a specific loop logic and returns an integer result based on the implementation.
      void onGameTick​(net.runelite.api.events.GameTick event)
      Handles actions to be executed on each game tick event while the script is running.
      void onStart()
      Optional: Called when the script starts.
      void onStop()
      Optional: Called when the script stops.
      void pause()
      Pauses the execution of the script.
      void resume()
      Resumes the execution of the script if it is currently paused.
      void start()
      Starts the script execution, initializing necessary components and marking the script as running.
      void stop()
      Gracefully stops a running asynchronous loop.
      void stop​(java.lang.Runnable callback)
      Stops the current execution loop and performs the necessary cleanup.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • Script

        public Script()
    • Method Detail

      • loop

        public abstract int loop()
        Executes a specific loop logic and returns an integer result based on the implementation.

        This abstract method needs to be implemented by subclasses to define the specific behavior of the loop.

        Returns:
        an integer value representing the amount of time to sleep in milliseconds. Since this is called every game tick, any value <= 600 will execute on the next game tick.

        Example Usage:

        {
         public class CustomScript extends Script {
             @Override
             public int loop() {
                 // Do something to automate the game
                 return 100;
             }
         }
         }
      • onStart

        public void onStart()
        Optional: Called when the script starts.
        Specified by:
        onStart in interface Scriptable
      • onStop

        public void onStop()
        Optional: Called when the script stops.
        Specified by:
        onStop in interface Scriptable
      • start

        public final void start()
        Starts the script execution, initializing necessary components and marking the script as running.

        This method transitions the script into a "running" state by performing the following steps:

        • Verifies if the script is already running; if so, the method returns immediately.
        • Sets the internal isRunning flag to true to indicate that the script is running.
        • Registers the script instance to the eventBus for event handling.
        • Generates a log entry indicating that the script has started.
        • Invokes the onStart() method to allow subclasses to define custom startup logic.

        Thread-Safety

        This method ensures thread-safe initialization of the script's state. However, external synchronization may be required if the method is invoked from multiple threads.

        Behavior

        • If the script is already running, no further actions are performed.
        • Otherwise, the script is initialized, event handling is enabled, and startup logic is executed.

        Example Usage

        Used during the initialization process of a script:

         
         // Called during the plugin's start-up phase to launch the script
         @Override
         protected void startUp() {
             context.register();
             context.initializePackets();
             exampleScript.start(); // Start the script
        
             overlayManager.add(overlay);
         }
         
         
      • pause

        public final void pause()
        Pauses the execution of the script.

        This method halts the script's execution by setting the internal isRunning flag to false. If the script is already paused, invoking this method will have no effect. A log entry is generated to indicate the transition to the paused state.

        Behavior

        • If the script is running (isRunning == true), the method sets isRunning to false and logs the pause action.
        • If the script is already paused or not running, the method performs no actions.

        Thread-Safety

        Ensure thread-safe access to the script's state when invoking this method to prevent race conditions.

        Example Usage

        Used when a configuration change should trigger the script to pause:

         
         @Subscribe
         private void onConfigChanged(final ConfigChanged event) {
             if (event.getGroup().equals("testapi") and event.getKey().equalsIgnoreCase("pauseScript")) {
                 if (config.pauseScript()) {
                     exampleScript.pause();
                 } else {
                     exampleScript.resume();
                 }
             }
         }
         
         
      • resume

        public final void resume()
        Resumes the execution of the script if it is currently paused.

        This method transitions the script's state to running by setting the internal isRunning flag to true. During this process, a log entry is generated to indicate that the script has been resumed. If the script is already running, this method does nothing.

        Behavior

        • If the script is paused (isRunning == false), the method sets isRunning to true and logs the resumption.
        • If the script is already running, the method performs no actions.

        Thread-Safety

        Ensure thread-safe access to the script's state before calling this method.

        Example Usage:

         
         @Subscribe
         private void onConfigChanged(final ConfigChanged event) {
             if (event.getGroup().equals("testapi") and event.getKey().equalsIgnoreCase("pauseScript")) {
                 if (config.pauseScript()) {
                     exampleScript.pause();
                 } else {
                     exampleScript.resume();
                 }
             }
         }
         
         
      • onGameTick

        @Subscribe
        public final void onGameTick​(net.runelite.api.events.GameTick event)
        Handles actions to be executed on each game tick event while the script is running.

        This method is triggered by the GameTick event, which occurs at consistent 0.6s intervals in the game. It coordinates the execution of the script's main logic by invoking the loop() method on a separate thread.

        Key Behavior:

        • Ensures that the script is running before proceeding. If isRunning is false, the method returns immediately.
        • Skips execution if a previous loop() call is still in progress, indicated by the future object.
        • Submits the loop() logic to an executor service for asynchronous execution.
        • If a delay is set by the loop() method, the thread sleeps for the specified duration before proceeding.
        • Gracefully handles and logs exceptions thrown during the loop execution.
        • Cleans up thread-local resources by calling RunnableTask.dispose().

        Threading Model:

        The main game logic defined in loop() is executed asynchronously to avoid blocking the main game thread. This separation allows for the use of thread sleeps and other blocking operations within the loop's logic.

        Parameters:
        event - an instance of GameTick representing a single tick of the game clock. It triggers all logic tied to the game's periodic updates.

        Example Usage:

         
         public class ExampleScript extends Script {
        
             @Override
             public int loop() {
                 log.info("Executing game logic...");
                 // Perform actions such as pathfinding or combat
                 return 1000; // Delay in milliseconds before the next execution
             }
         }
         
         
      • stop

        public void stop​(java.lang.Runnable callback)
        Stops the current execution loop and performs the necessary cleanup. This method safely shuts down the process, unregisters the instance from the event bus, and triggers the provided callback after successful termination.

        Behavior:

        • Sets the running status to false if the process is active.
        • Unregisters the instance from the event bus.
        • Cancels the associated RunnableTask.
        • Waits for the asynchronous future to complete before invoking the callback.
        Specified by:
        stop in interface Scriptable
        Parameters:
        callback - A Runnable that will execute after the stop operation is complete; can be null if no action is required after stopping.
      • stop

        public void stop()
        Gracefully stops a running asynchronous loop.