001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.wpilibj2.command;
006
007import static edu.wpi.first.wpilibj.util.ErrorMessages.requireNonNullParam;
008
009/**
010 * A command that runs a given runnable when it is initialized, and another runnable when it ends.
011 * Useful for running and then stopping a motor, or extending and then retracting a solenoid. Has no
012 * end condition as-is; either subclass it or use {@link Command#withTimeout(double)} or {@link
013 * Command#withInterrupt(java.util.function.BooleanSupplier)} to give it one.
014 */
015public class StartEndCommand extends CommandBase {
016  protected final Runnable m_onInit;
017  protected final Runnable m_onEnd;
018
019  /**
020   * Creates a new StartEndCommand. Will run the given runnables when the command starts and when it
021   * ends.
022   *
023   * @param onInit the Runnable to run on command init
024   * @param onEnd the Runnable to run on command end
025   * @param requirements the subsystems required by this command
026   */
027  public StartEndCommand(Runnable onInit, Runnable onEnd, Subsystem... requirements) {
028    m_onInit = requireNonNullParam(onInit, "onInit", "StartEndCommand");
029    m_onEnd = requireNonNullParam(onEnd, "onEnd", "StartEndCommand");
030
031    addRequirements(requirements);
032  }
033
034  @Override
035  public void initialize() {
036    m_onInit.run();
037  }
038
039  @Override
040  public void end(boolean interrupted) {
041    m_onEnd.run();
042  }
043}