Class BackgroundWorker

java.lang.Object
com.crossbotics.ftchelper.util.BackgroundWorker

public final class BackgroundWorker extends Object
Runs slow jobs (a network request, a camera setting) on a separate thread, so the robot's loop never waits for them. Used inside the library (Limelight requests, webcam exposure).

A "thread" is a second line of work that runs at the same time as your OpMode's loop, like a helper who goes off to make a phone call while you keep driving. Your loop hands the helper a job and carries on at once; the helper does the slow waiting.


 BackgroundWorker worker = new BackgroundWorker("limelight");
 worker.submitLatest("heading", () -> limelight.updateRobotOrientation(heading)); // returns at once
 ...
 worker.shutdown();     // at the end of the OpMode
 

submitLatest(java.lang.String, java.lang.Runnable) keeps only the NEWEST job for a key: if the robot asks 50 times per second and the network can do 20, the worker sends the latest value and skips the old ones, so the queue never grows. Jobs must not touch motors or servos (do that in the loop).

Why no motors or servos in a job? Only the loop should control them, so that STOP, limits and safety checks always see everything. Two threads giving a motor orders would fight. Docs: docs/guides/non-blocking.md

  • Constructor Details

    • BackgroundWorker

      public BackgroundWorker(String name)
      Starts the worker thread (a daemon: it never keeps the app alive).
      Parameters:
      name - a short name, shown in error reports, e.g. "limelight"
  • Method Details

    • submit

      public void submit(Runnable job)
      Queues a job. Returns at once.
      Parameters:
      job - the work to do; () -> ... is a small piece of code to run later
    • submitLatest

      public void submitLatest(String key, Runnable job)
      Queues a job, replacing a waiting job with the same key (only the newest one runs). Returns at once.
      Parameters:
      key - a name for this kind of job, e.g. "heading"; a newer job with the same key replaces it
      job - the work to do
    • queued

      public int queued()
      Jobs waiting to run.
    • getLastError

      public String getLastError()
      "" or the last error a job threw (jobs never crash the robot).
    • shutdown

      public void shutdown()
      Stops the thread. Jobs still waiting are dropped. Returns at once.
    • isRunning

      public boolean isRunning()
      True until shutdown().