@Test
  public void testMultipleManualInstances() throws Exception {
    TaskScheduleUtil.waitForAllTasksToStop();
    getEventInspectorsUtil().waitForCalmPeriod();

    createSnapshotTask("Nexus1650Task1");
    createSnapshotTask("Nexus1650Task2");
    createSnapshotTask("Nexus1650Task3");

    List<ScheduledServiceListResource> tasks = TaskScheduleUtil.getTasks();

    assertThat(tasks, hasSize(3));

    long startTimestamp = System.currentTimeMillis();

    for (ScheduledServiceListResource resource : tasks) {
      TaskScheduleUtil.run(resource.getId());
    }

    waitForOneTaskSleeping();

    TaskScheduleUtil.waitForAllTasksToStop();

    assertAllTasksWereRunning(startTimestamp);
  }
  private void assertAllTasksWereRunning(long startTimestamp) throws IOException {
    final List<ScheduledServiceListResource> tasks = TaskScheduleUtil.getTasks();

    for (ScheduledServiceListResource task : tasks) {
      assertThat(
          "task did not run properly!", task.getLastRunTimeInMillis(), greaterThan(startTimestamp));
    }
  }
  private boolean isAtLeastOneSleeping() throws Exception {
    List<ScheduledServiceListResource> tasks = TaskScheduleUtil.getTasks();

    for (ScheduledServiceListResource resource : tasks) {
      if (resource.getStatus().equals("SLEEPING")) {
        return true;
      }
    }

    return false;
  }
    public String getTasksAsJson() {

      Map<String, List<String>> taskNameLists = new HashMap<String, List<String>>();

      for (NexusDescriptor desc : nexusMap.values()) {
        NexusClient client =
            new NexusJerseyClient(desc.getUrl(), desc.getUser(), desc.getPassword());
        client.init();
        if (client.ping()) {
          List<ScheduledServiceListResource> serviceList =
              client.get("schedules", ScheduledServiceListResourceResponse.class).getData();
          if (serviceList != null && serviceList.size() > 0) {
            List<String> serviceNameList = new ArrayList<String>();
            for (ScheduledServiceListResource servise : serviceList) {
              serviceNameList.add(servise.getName());
            }
            taskNameLists.put(desc.getName(), serviceNameList);
          }
        }
      }

      return JSONObject.fromObject(taskNameLists).toString();
    }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {

    listener.getLogger().println("Start to submit Nexus scheduled tasks.");

    // Verify configuration of Nexus is still valid.
    if (selectedNexus == null) {
      listener.getLogger().println("Nexus you choise is invalid.");
      listener.getLogger().println("Please check your Jenkins's configuration.");
      return false;
    }

    // Verify Nexus is running.
    NexusClient client =
        new NexusJerseyClient(
            selectedNexus.getUrl(), selectedNexus.getUser(), selectedNexus.getPassword());
    client.init();
    if (!client.ping()) {
      listener
          .getLogger()
          .println(
              "Fail to connect Nexus. URL: "
                  + selectedNexus.getUrl()
                  + ", User: "******"Please check your Nexus is working.");
      return false;
    }

    TaskUtil taskUtil = new TaskUtil(client);

    // List<TaskStatus> statusList = new ArrayList<TaskStatus>();

    // Build ToDo list
    List<ScheduledServiceListResource> todoList = new ArrayList<ScheduledServiceListResource>();

    for (String taskName : tasks.split(",\\s*")) {
      if (!taskName.matches("\\s*")) {
        List<ScheduledServiceListResource> queryResults = taskUtil.fastFetchTasks(taskName);
        if (queryResults != null) {
          todoList.addAll(queryResults);
        } else {
          listener
              .getLogger()
              .println("WARNING: There is no shceduled task whose name is " + taskName + ".");
        }
      }
    }

    // Execute tasks.
    TaskRunner runner = new TaskRunner(client);
    for (ScheduledServiceListResource task : todoList) {
      TaskStatus status = runner.exec(task.getId());
      listener
          .getLogger()
          .println(
              "Submitting... [id: "
                  + task.getId()
                  + ", name: "
                  + task.getName()
                  + ", type: "
                  + task.getTypeName()
                  + "]");
      if (status.equals(TaskStatus.NG) || status.equals(TaskStatus.NG_UNKNOWN)) {
        listener.getLogger().println(task.getId() + ": Return NG status. Please Check your Nexus.");
        return false;
      } else if (status.equals(TaskStatus.WARNING_STILL_RUNNING)) {
        listener
            .getLogger()
            .println("WARNING: This task is still running. Jenkins skipped queueing.");
      }
    }

    listener.getLogger().println("End to submit Nexus scheduled tasks successfully.");
    return true;
  }
  /**
   * Retrieve a list of scheduled tasks currently configured in nexus.
   *
   * @param allTasks If true, will return all tasks, even non-exposed tasks.
   */
  @Override
  @GET
  @ResourceMethodSignature(output = ScheduledServiceListResourceResponse.class)
  public Object get(Context context, Request request, Response response, Variant variant)
      throws ResourceException {
    boolean allTasks = isAllTasks(request);

    Map<String, List<ScheduledTask<?>>> tasksMap = getNexusScheduler().getAllTasks();

    ScheduledServiceListResourceResponse result = new ScheduledServiceListResourceResponse();

    for (String key : tasksMap.keySet()) {
      List<ScheduledTask<?>> tasks = tasksMap.get(key);

      for (ScheduledTask<?> task : tasks) {
        boolean isExposed = true;

        SchedulerTask<?> st = task.getSchedulerTask();

        if (st != null && st instanceof NexusTask<?>) {
          isExposed = ((NexusTask<?>) st).isExposed();
        }

        if (allTasks || isExposed) {
          if (getLogger().isDebugEnabled()) {
            getLogger()
                .debug("Building task '" + task.getName() + "' of type '" + task.getType() + "'.");
          }

          ScheduledServiceListResource item = new ScheduledServiceListResource();
          item.setResourceURI(createChildReference(request, this, task.getId()).toString());
          item.setLastRunResult(getLastRunResult(task));
          item.setId(task.getId());
          item.setName(task.getName());
          item.setStatus(task.getTaskState().toString());
          item.setReadableStatus(getReadableState(task.getTaskState()));
          item.setTypeId(task.getType());
          ScheduledTaskDescriptor descriptor =
              getNexusConfiguration().getScheduledTaskDescriptor(task.getType());
          if (descriptor != null) {
            item.setTypeName(descriptor.getName());
          }
          item.setCreated(task.getScheduledAt() == null ? "n/a" : task.getScheduledAt().toString());
          item.setLastRunTime(task.getLastRun() == null ? "n/a" : task.getLastRun().toString());
          final Date nextRunTime = getNextRunTime(task);
          item.setNextRunTime(nextRunTime == null ? "n/a" : nextRunTime.toString());
          if (task.getScheduledAt() != null) {
            item.setCreatedInMillis(task.getScheduledAt().getTime());
          }
          if (task.getLastRun() != null) {
            item.setLastRunTimeInMillis(task.getLastRun().getTime());
          }
          if (nextRunTime != null) {
            item.setNextRunTimeInMillis(nextRunTime.getTime());
          }
          item.setSchedule(getScheduleShortName(task.getSchedule()));
          item.setEnabled(task.isEnabled());

          result.addData(item);
        }
      }
    }

    return result;
  }