<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def wait(self, timeout=None):
 """ Wait for command to finish. @param timeout: (Optional) Max amount of time (in seconds) to wait. Wait forever by default. @return: The final ApiCommand object, containing the last known state. The command may still be running in case of timeout. """

    if self.id == ApiCommand.SYNCHRONOUS_COMMAND_ID:
      return self

    SLEEP_SEC = 5

    if timeout is None:
      deadline = None
    else:
      deadline = time.time() + timeout

    while True:
      cmd = self.fetch()
      if not cmd.active:
        return cmd

      if deadline is not None:
        now = time.time()
        if deadline < now:
          return cmd
        else:
          time.sleep(min(SLEEP_SEC, deadline - now))
      else:
        time.sleep(SLEEP_SEC)