RobotCore 1.0
WPILib port to raspberry Pi
Loading...
Searching...
No Matches
org.wpilib.command3.Scheduler Class Reference
Inheritance diagram for org.wpilib.command3.Scheduler:
org.wpilib.util.protobuf.ProtobufSerializable org.wpilib.util.WPISerializable

Classes

interface  ScheduleResult

Public Member Functions

void setDefaultCommand (Mechanism mechanism, Command defaultCommand)
Command getDefaultCommandFor (Mechanism mechanism)
void sideload (Consumer< Coroutine > callback)
void addPeriodic (Runnable callback)
ScheduleResult isSchedulable (Command command)
ScheduleResult schedule (Command command)
void cancel (Command command)
void run ()
Command currentCommand ()
boolean isRunning (Command command)
boolean isScheduled (Command command)
boolean isScheduledOrRunning (Command command)
Collection< Command > getRunningCommands ()
List< Command > getRunningCommandsFor (Mechanism mechanism)
void cancelAll ()
EventLoop getDefaultEventLoop ()
Collection< Command > getQueuedCommands ()
Command getParentOf (Command command)
double lastCommandRuntimeMs (Command command)
double totalRuntimeMs (Command command)
int runId (Command command)
double lastRuntimeMs ()
void addEventListener (Consumer<? super SchedulerEvent > listener)

Static Public Member Functions

static Scheduler getDefault ()
static Scheduler createIndependentScheduler ()

Static Public Attributes

static final SchedulerProto proto = new SchedulerProto()

Detailed Description

Manages the lifecycles of Coroutine-based Commands. Commands may be scheduled directly using schedule(Command), or be bound to Triggers to automatically handle scheduling and cancellation based on internal or external events. User code is responsible for calling run() periodically to update trigger conditions and execute scheduled commands. Most often, this is done by overriding TimedRobot#robotPeriodic() to include a call to Scheduler.getDefault().run():


public class Robot extends TimedRobot {
@Override
public void robotPeriodic() {
// Update the scheduler on every loop
Scheduler.getDefault().run();
}
}

Danger

The scheduler must be used in a single-threaded program. Commands must be scheduled and canceled by the same thread that runs the scheduler, and cannot be run in a virtual thread.

Using the commands framework in a multithreaded environment can cause crashes in the Java virtual machine at any time, including on an official field during a match. The Java JIT compilers make assumptions that rely on coroutines being used on a single thread. Breaking those assumptions can cause incorrect JIT code to be generated with undefined behavior, potentially causing control issues or crashes deep in JIT-generated native code.

Normal concurrency constructs like locks, atomic references, and synchronized blocks or methods cannot save you.

Lifecycle

The run() method runs six steps:

  1. Cancel any commands bound to scopes that have gone inactive, such as having been scheduled in an opmode that's no longer selected on the driverstation.
  2. Cancel any triggers that were created in scopes that have gone inactive, such as being constructed in an opmode that's no longer selected on the driverstation.
  3. Call periodic sideload functions.
  4. Poll all registered triggers to queue and cancel commands.
  5. Queue default commands for any mechanisms without a running command. The queued commands can be superseded by any manual scheduling or commands scheduled by triggers in the next run.
  6. Start all queued commands. This happens after all triggers are checked in case multiple commands with conflicting requirements are queued in the same update; the last command to be queued takes precedence over the rest.
  7. Loop over all running commands, mounting and calling each in turn until they either exit or call Coroutine#yield(). Commands run in the order in which they were scheduled.

Telemetry

There are two mechanisms for telemetry for a scheduler. A protobuf serializer can be used to take a snapshot of a scheduler instance, and report what commands are queued (scheduled but have not yet started to run), commands that are running (along with timing data for each command), and total time spent in the most recent run() call. However, it cannot detect one-shot commands that are scheduled, run, and complete all in a single run() invocation - effectively, commands that never call Coroutine#yield() are invisible.

A second telemetry mechanism is provided by addEventListener(Consumer). The scheduler will issue events to all registered listeners when certain events occur (see SchedulerEvent for all event types). These events are emitted immediately and can be used to detect lifecycle events for all commands, including one-shots that would be invisible to the protobuf serializer. However, it is up to the user to log those events themselves.

Definition at line 106 of file Scheduler.java.

Member Function Documentation

◆ addEventListener()

void org.wpilib.command3.Scheduler.addEventListener ( Consumer<? super SchedulerEvent > listener)

Adds a listener to handle events that are emitted by the scheduler. Events are emitted when certain actions are taken by user code or by internal processing logic in the scheduler. Listeners should take care to be quick, simple, and not schedule or cancel commands, as that may cause inconsistent scheduler behavior or even cause a program crash.

Listeners are primarily expected to be for data logging and telemetry. In particular, a one-shot command (one that never calls Coroutine#yield()) will never appear in the standard protobuf telemetry because it is scheduled, runs, and finishes all in a single scheduler cycle. However, SchedulerEvent.Scheduled,SchedulerEvent.Mounted, and SchedulerEvent.Completed events will be emitted corresponding to those actions, and user code can listen for and log such events.

Parameters
listenerThe listener to add. Cannot be null.
Exceptions
NullPointerExceptionif given a null listener

Definition at line 1490 of file Scheduler.java.

◆ addPeriodic()

void org.wpilib.command3.Scheduler.addPeriodic ( Runnable callback)

Adds a periodic callback to run as part of the scheduler. The callback should not manipulate or control any mechanisms, but can be used to log information, update data (such as simulations or LED data buffers), or perform some other helpful task.

For example:


scheduler.addPeriodic(() -> leds.setData(ledDataBuffer));
scheduler.addPeriodic(() -> {
SmartDashboard.putNumber("X", getX());
SmartDashboard.putNumber("Y", getY());
});

addPeriodic is a convenience method that is identical to using sideload(Consumer) with an unending while loop:


// An addPeriodic call:
scheduler.addPeriodic(() -> leds.setData(ledDataBuffer));

// Is equivalent to this sideload call:
scheduler.sideload(coroutine -> {
while (true) {
leds.setData(ledDataBuffer)
coroutine.yield();
}
});
Parameters
callbackthe periodic function to run
See also
#sideload(Consumer)

Definition at line 330 of file Scheduler.java.

◆ cancel()

void org.wpilib.command3.Scheduler.cancel ( Command command)

Cancels a command and any other command scheduled by it. This occurs immediately and does not need to wait for a call to run(). Any command that it scheduled will also be canceled to ensure commands within compositions do not continue to run.

This has no effect if the given command is not currently scheduled or running.

Parameters
commandthe command to cancel

Definition at line 776 of file Scheduler.java.

◆ cancelAll()

void org.wpilib.command3.Scheduler.cancelAll ( )

Cancels all currently running and scheduled commands. All default commands will be scheduled on the next call to run(), unless a higher priority command is scheduled or triggered after cancelAll() is used.

Definition at line 1297 of file Scheduler.java.

◆ createIndependentScheduler()

Scheduler org.wpilib.command3.Scheduler.createIndependentScheduler ( )
static

Creates a new scheduler object. Note that most built-in constructs like Trigger and CommandGenericHID will use the default scheduler instance unless they were explicitly constructed with a different scheduler instance. Teams should use the default instance for convenience; however, new scheduler instances can be useful for unit tests.

Returns
a new scheduler instance that is independent of the default scheduler instance.

Definition at line 185 of file Scheduler.java.

◆ currentCommand()

Command org.wpilib.command3.Scheduler.currentCommand ( )

Gets the currently executing command, or null if no command is currently executing.

Returns
the currently executing command

Definition at line 1151 of file Scheduler.java.

◆ getDefault()

Scheduler org.wpilib.command3.Scheduler.getDefault ( )
static

Gets the default scheduler instance for use in a robot program. Unless otherwise specified, triggers and mechanisms will be registered with the default scheduler and require the default scheduler to run. However, triggers and mechanisms can be constructed to be registered with a specific scheduler instance, which may be useful for isolation for unit tests.

Returns
the default scheduler instance.

Definition at line 171 of file Scheduler.java.

◆ getDefaultCommandFor()

Command org.wpilib.command3.Scheduler.getDefaultCommandFor ( Mechanism mechanism)

Gets the default command currently used for a mechanism.

Parameters
mechanismThe mechanism
Returns
The default command, or null if no default command was ever set

Definition at line 252 of file Scheduler.java.

◆ getDefaultEventLoop()

EventLoop org.wpilib.command3.Scheduler.getDefaultEventLoop ( )

An event loop used by the scheduler to poll triggers that schedule or cancel commands. This event loop is always polled on every call to run(). Custom event loops need to be bound to this one for synchronicity with the scheduler; however, they can always be polled manually before or after the call to run().

Returns
the default event loop.

Definition at line 1325 of file Scheduler.java.

◆ getParentOf()

Command org.wpilib.command3.Scheduler.getParentOf ( Command command)

For internal use.

Parameters
commandThe command to check
Returns
The command that forked the provided command. Null if the command is not a child of another command.

Definition at line 1357 of file Scheduler.java.

◆ getQueuedCommands()

Collection< Command > org.wpilib.command3.Scheduler.getQueuedCommands ( )

For internal use.

Returns
The commands that have been scheduled but not yet started.

Definition at line 1335 of file Scheduler.java.

◆ getRunningCommands()

Collection< Command > org.wpilib.command3.Scheduler.getRunningCommands ( )

Gets the set of all currently running commands. Commands are returned in the order in which they were scheduled. The returned set is read-only.

Returns
the currently running commands

Definition at line 1275 of file Scheduler.java.

◆ getRunningCommandsFor()

List< Command > org.wpilib.command3.Scheduler.getRunningCommandsFor ( Mechanism mechanism)

Gets all the currently running commands that require a particular mechanism. Commands are returned in the order in which they were scheduled. The returned list is read-only.

Parameters
mechanismthe mechanism to get the commands for
Returns
the currently running commands that require the mechanism.

Definition at line 1286 of file Scheduler.java.

◆ isRunning()

boolean org.wpilib.command3.Scheduler.isRunning ( Command command)

Checks if a command is currently running.

Parameters
commandthe command to check
Returns
true if the command is running, false if not

Definition at line 1244 of file Scheduler.java.

◆ isSchedulable()

ScheduleResult org.wpilib.command3.Scheduler.isSchedulable ( Command command)

Checks if a command is able to be scheduled. Returns of the following states:

  • AlreadyRunning if the command is already scheduled or running.
  • Success if the command is not already scheduled or running and does not conflict with any other scheduled or running commands. The associated run ID will be 0, rather than an actual run ID, because the command will not have actually been scheduled and received an ID.
  • LowerPriorityThanRunningCommand if the command has a lower priority than a running command that shares requirements
  • LowerPriorityThanQueuedCommand if the command has a lower priority than a queued command that shares requirements
  • RequiresUnsafeMechanisms if the command requires mechanisms that are not controllable when the robot is disabled.
Parameters
commandThe command to check. Cannot be null.
Returns
A schedule result indicating the schedulability of the command.

Definition at line 467 of file Scheduler.java.

◆ isScheduled()

boolean org.wpilib.command3.Scheduler.isScheduled ( Command command)

Checks if a command is currently scheduled to run, but is not yet running.

Parameters
commandthe command to check
Returns
true if the command is scheduled to run, false if not

Definition at line 1255 of file Scheduler.java.

◆ isScheduledOrRunning()

boolean org.wpilib.command3.Scheduler.isScheduledOrRunning ( Command command)

Checks if a command is currently scheduled to run, or is already running.

Parameters
commandthe command to check
Returns
true if the command is scheduled to run or is already running, false if not

Definition at line 1265 of file Scheduler.java.

◆ lastCommandRuntimeMs()

double org.wpilib.command3.Scheduler.lastCommandRuntimeMs ( Command command)

Gets how long a command took to run in the previous cycle. If the command is not currently running, returns -1.

Parameters
commandThe command to check
Returns
How long, in milliseconds, the command last took to execute.

Definition at line 1372 of file Scheduler.java.

◆ lastRuntimeMs()

double org.wpilib.command3.Scheduler.lastRuntimeMs ( )

Gets how long the scheduler took to process its most recent run() invocation, in milliseconds. Defaults to -1 if the scheduler has not yet run.

Returns
How long, in milliseconds, the scheduler last took to execute.

Definition at line 1427 of file Scheduler.java.

◆ run()

void org.wpilib.command3.Scheduler.run ( )

Updates the command scheduler. This will run operations in the following order:

  1. Cancel any commands bound to scopes that have gone inactive, such as having been scheduled in an opmode that's no longer selected on the driverstation
  2. Cancel any triggers that were created in scopes that have gone inactive, such as being constructed in an opmode that's no longer selected on the driverstation
  3. Run sideloaded functions from sideload(Consumer) and addPeriodic(Runnable)
  4. Update trigger bindings to queue and cancel bound commands
  5. Queue default commands for mechanisms that do not have a queued or running command
  6. Promote queued commands to the running set
  7. For every command in the running set, mount and run that command until it calls Coroutine#yield() or exits

This method is intended to be called in a periodic loop like TimedRobot#robotPeriodic()

Definition at line 829 of file Scheduler.java.

◆ runId()

int org.wpilib.command3.Scheduler.runId ( Command command)

Gets the unique run id for a scheduled or running command. If the command is not currently scheduled or running, this function returns 0.

Parameters
commandThe command to get the run ID for
Returns
The run of the command

Definition at line 1405 of file Scheduler.java.

◆ schedule()

ScheduleResult org.wpilib.command3.Scheduler.schedule ( Command command)

Schedules a command to run. If one command schedules another (a "parent" and "child"), the child command will be canceled when the parent command completes. It is not possible to fork a child command and have it live longer than its parent.

Does nothing if the command is already scheduled or running, or requires at least one mechanism already used by a higher priority command.

For purposes of scheduling, a child command is considered to have a priority equal to the highest priority in its scheduling hierarchy. For example, if a parent command with priority 10 schedules a child command with priority 5, the child command will be treated as having a priority of 10 and will interrupt any conflicting command with a priority of 10 or lower, rather than the usual 5.

Parameters
commandthe command to schedule
Returns
the result of the scheduling attempt. See ScheduleResult for details.
Exceptions
IllegalArgumentExceptionif scheduled by a command composition that has already scheduled another command that shares at least one required mechanism

Definition at line 574 of file Scheduler.java.

◆ setDefaultCommand()

void org.wpilib.command3.Scheduler.setDefaultCommand ( Mechanism mechanism,
Command defaultCommand )

Sets the default command for a mechanism. The command must require that mechanism and cannot require any other mechanisms. If another default command has already been set for this mechanism, the one provided will supersede it.

If this is called inside a running opmode or in a running command, the default command setting will only apply while that opmode or command is active. When the opmode or command exits, the previous default command setting will be restored.

Commands running as default commands may call this method to change their mechanism's default command on the fly. The new default command will take effect at the end of the scheduler's loop cycle.

Parameters
mechanismthe mechanism for which to set the default command
defaultCommandthe default command to execute on the mechanism
Exceptions
IllegalArgumentExceptionif the command does not meet the requirements for being a default command

Definition at line 211 of file Scheduler.java.

◆ sideload()

void org.wpilib.command3.Scheduler.sideload ( Consumer< Coroutine > callback)

Adds a callback to run as part of the scheduler. The callback should not manipulate or control any mechanisms, but can be used to log information, update data (such as simulations or LED data buffers), or perform some other helpful task. The callback is responsible for managing its own control flow and end conditions. If you want to run a single task periodically for the entire lifespan of the scheduler, use addPeriodic(Runnable).

Note: Like commands, any loops in the callback must appropriately yield control back to the scheduler with Coroutine#yield or risk stalling your program in an unrecoverable infinite loop!

The coroutines provided to sideloaded functions will not cancel themselves if a fork or await call fails. This allows user code the opportunity to recover from a failure. You can opt into canceling the coroutine if a fork or await call fails by calling Coroutine#setCancelOnForkFailure(boolean).

Parameters
callbackthe callback to sideload
See also
addPeriodic(Runnable)

Definition at line 285 of file Scheduler.java.

◆ totalRuntimeMs()

double org.wpilib.command3.Scheduler.totalRuntimeMs ( Command command)

Gets how long a command has taken to run, in aggregate, since it was most recently scheduled. If the command is not currently running, returns -1.

Parameters
commandThe command to check
Returns
How long, in milliseconds, the command has taken to execute in total

Definition at line 1387 of file Scheduler.java.

Member Data Documentation

◆ proto

final SchedulerProto org.wpilib.command3.Scheduler.proto = new SchedulerProto()
static

Protobuf serializer for a scheduler.

Definition at line 153 of file Scheduler.java.


The documentation for this class was generated from the following file: