exception: group "tasks". These are only executed if processshortname matches
179958
public List<StarterClientArgs> getToStart() {
        return toStart.stream().filter( sca -> {
            if ( ( !"tasks".equals(sca.getGroup()) && // either group is given (and its not "tasks"!!)
                    ( groups == null || groups.size() == 0 || (sca.getGroup() != null && groups.contains(sca.getGroup())) )
                 )
                 || (sca.getProcessShortName() != null && groups.contains(sca.getProcessShortName())) ) // "tasks" group members need to get started by name
            {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
    }
1326100
private void cancelTasksOfProcessInstance(ProcessInstance procInst)
    throws NamingException, JMSException, SQLException, ServiceLocatorException, MdwException {
        List<ProcessInstance> processInstanceList =
            edao.getChildProcessInstances(procInst.getId());
        List<Long> procInstIds = new ArrayList<Long>();
        procInstIds.add(procInst.getId());
        for (ProcessInstance pi : processInstanceList) {
            Process pidef = getProcessDefinition(pi);
            if (pidef.isEmbeddedProcess())
                procInstIds.add(pi.getId());
        }
        TaskServices taskServices = ServiceLocator.getTaskServices();
        for (Long procInstId : procInstIds) {
            taskServices.cancelTaskInstancesForProcess(procInstId);
        }
    }
377499
public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException {
        final String procedureName = "@ExecuteTask";
        Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName);
        Procedure proc = procedureConfig.asCatalogProcedure();
        StoredProcedureInvocation spi = new StoredProcedureInvocation();
        spi.setProcName(procedureName);
        spi.setParams(params);
        spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb));
        if (spi.getSerializedParams() == null) {
            spi = MiscUtils.roundTripForCL(spi);
        }
        synchronized (m_executeTaskAdpater) {
            m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi,
                    proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(),
                    new int[] { 0 } /* Can provide anything for multi-part */,
                    spi.getSerializedSize(), System.nanoTime());
        }
    }
545826
private byte[] collectProcessResultsBytes(Process process, ProcessBuilder builder,
      SubProcessIOFiles outPutFiles) throws Exception {

    Byte[] results;

    try {

      LOG.debug(String.format("Executing process %s", createLogEntryFromInputs(builder.command())));

      // If process exit value is not 0 then subprocess failed, record logs
      if (process.exitValue() != 0) {
        outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder));
        String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles);
        throw new Exception(log);
      }

      // If no return file then either something went wrong or the binary is setup incorrectly for
      // the ret file either way throw error
      if (!Files.exists(outPutFiles.resultFile)) {
        String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles);
        outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder));
        throw new Exception(log);
      }

      // Everything looks healthy return bytes
      return Files.readAllBytes(outPutFiles.resultFile);

    } catch (Exception ex) {
      String log = String.format("Unexpected error runnng process. %s error message was %s",
          createLogEntryFromInputs(builder.command()), ex.getMessage());
      throw new Exception(log);
    }
  }
347830
private void doPreemptionNow() {
    int totalShare = nodeManager.getAllocatedCpuForType(type);
    poolGroupManager.distributeShare(totalShare);
    for (PoolGroupSchedulable poolGroup : poolGroupManager.getPoolGroups()) {
      poolGroup.distributeShare();
    }
    int tasksToPreempt = countTasksShouldPreempt();
    if (tasksToPreempt > 0) {
      LOG.info("Found " + tasksToPreempt + " " + type + " tasks to preempt");
      preemptTasks(tasksToPreempt);
    }
  }
680921
private void addTask(Prop configProp, String configName) throws Exception {
		String configNameValue = configProp.get(configName);
		if (StrKit.isBlank(configNameValue)) {
			throw new IllegalArgumentException("The value of configName: " + configName + " can not be blank.");
		}
		String[] taskNameArray = configNameValue.trim().split(",");
		for (String taskName : taskNameArray) {
			if (StrKit.isBlank(taskName)) {
				throw new IllegalArgumentException("taskName can not be blank.");
			}
			taskName = taskName.trim();

			String taskCron = configProp.get(taskName + ".cron");
			if (StrKit.isBlank(taskCron)) {
				throw new IllegalArgumentException(taskName + ".cron" + " not found.");
			}
			taskCron = taskCron.trim();

			String taskClass = configProp.get(taskName + ".class");
			if (StrKit.isBlank(taskClass)) {
				throw new IllegalArgumentException(taskName + ".class" + " not found.");
			}
			taskClass = taskClass.trim();

			Object taskObj = Class.forName(taskClass).newInstance();
			if ( !(taskObj instanceof Runnable) && !(taskObj instanceof Task) ) {
				throw new IllegalArgumentException("Task 必须是 Runnable、ITask、ProcessTask 或者 Task 类型");
			}

			boolean taskDaemon  = configProp.getBoolean(taskName + ".daemon", true);
			boolean taskEnable  = configProp.getBoolean(taskName + ".enable", true);
			taskInfoList.add(new TaskInfo(taskCron, taskObj, taskDaemon, taskEnable));
		}
	}
682309
protected void performSubtasks(TaskRequest req, TaskResponse res, List<Task> tasks) {
        // Assertions...
        if (req == null) {
            String msg = "Argument 'req' cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        if (res == null) {
            String msg = "Argument 'res' cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        if (tasks == null) {
            String msg = "Child tasks have not been initialized.  Subclasses "
                            + "of AbstractContainerTask must call super.init() "
                            + "within their own init() method.";
            throw new IllegalStateException(msg);
        }
        
        // Invoke each of our children...
        for (Task k : tasks) {
            k.perform(req, res);
        }
	}
1043034
public static void main(String[] args) {
        try {
            if (args.length < 1) {
                System.err.println();
                System.err.println(Globals.getWorkbenchInfoString());
                System.err.println();
                System.err.println("No task specified.");
            } else {
                if (isJavaVersionOK() == false || WekaUtils.isWekaVersionOK() == false) {
                    return;
                }
                // create standard options
                FlagOption suppressStatusOutputOption = new FlagOption(
                        "suppressStatusOutput", 'S',
                        "Suppress the task status output that is normally send to stderr.");
                FlagOption suppressResultOutputOption = new FlagOption(
                        "suppressResultOutput", 'R',
                        "Suppress the task result output that is normally send to stdout.");
                IntOption statusUpdateFrequencyOption = new IntOption(
                        "statusUpdateFrequency",
                        'F',
                        "How many milliseconds to wait between status updates.",
                        1000, 0, Integer.MAX_VALUE);
                Option[] extraOptions = new Option[]{
                    suppressStatusOutputOption, suppressResultOutputOption,
                    statusUpdateFrequencyOption};
                // build a single string by concatenating cli options
                StringBuilder cliString = new StringBuilder();
                for (int i = 0; i < args.length; i++) {
                    cliString.append(" ").append(args[i]);
                }
                // parse options
                AbstractTask task;
                try {
                	task = (AbstractTask) ClassOption.cliStringToObject(
                			cliString.toString(), MainTask.class, extraOptions);
                } catch(Exception e) {
                	// regular task could not be found, maybe it is a meta task
            		task = (AbstractTask) ClassOption.cliStringToObject(
            				cliString.toString(), MetaMainTask.class, extraOptions);
                }
                task.prepareForUse();
                
                Object result = null;
                if (suppressStatusOutputOption.isSet()) {
                    result = task.doTask();
                } else {
                    System.err.println();
                    System.err.println(Globals.getWorkbenchInfoString());
                    System.err.println();
                    boolean preciseTiming = TimingUtils.enablePreciseTiming();
                    // start the task thread
                    TaskThread taskThread = new TaskThread(task);
                    taskThread.start();
                    int progressAnimIndex = 0;
                    // inform user of progress
                    while (!taskThread.isComplete()) {
                        StringBuilder progressLine = new StringBuilder();
                        progressLine.append(progressAnimSequence[progressAnimIndex]);
                        progressLine.append(' ');
                        progressLine.append(StringUtils.secondsToDHMSString(taskThread.getCPUSecondsElapsed()));
                        progressLine.append(" [");
                        progressLine.append(taskThread.getCurrentStatusString());
                        progressLine.append("] ");
                        double fracComplete = taskThread.getCurrentActivityFracComplete();
                        if (fracComplete >= 0.0) {
                            progressLine.append(StringUtils.doubleToString(
                                    fracComplete * 100.0, 2, 2));
                            progressLine.append("% ");
                        }
                        progressLine.append(taskThread.getCurrentActivityString());
                        while (progressLine.length() < MAX_STATUS_STRING_LENGTH) {
                            progressLine.append(" ");
                        }
                        if (progressLine.length() > MAX_STATUS_STRING_LENGTH) {
                            progressLine.setLength(MAX_STATUS_STRING_LENGTH);
                            progressLine.setCharAt(
                                    MAX_STATUS_STRING_LENGTH - 1, '~');
                        }
                        System.err.print(progressLine.toString());
                        System.err.print('\r');
                        if (++progressAnimIndex >= progressAnimSequence.length) {
                            progressAnimIndex = 0;
                        }
                        try {
                            Thread.sleep(statusUpdateFrequencyOption.getValue());
                        } catch (InterruptedException ignored) {
                            // wake up
                        }
                    }
                    StringBuilder cleanupString = new StringBuilder();
                    for (int i = 0; i < MAX_STATUS_STRING_LENGTH; i++) {
                        cleanupString.append(' ');
                    }
                    System.err.println(cleanupString);
                    result = taskThread.getFinalResult();
                    if (!(result instanceof FailedTaskReport)) {
                        System.err.print("Task completed in "
                                + StringUtils.secondsToDHMSString(taskThread.getCPUSecondsElapsed()));
                        if (preciseTiming) {
                            System.err.print(" (CPU time)");
                        }
                        System.err.println();
                        System.err.println();
                    }
                }
                if (result instanceof FailedTaskReport) {
                    System.err.println("Task failed. Reason: ");
                    ((FailedTaskReport) result).getFailureReason().printStackTrace();
                } else {
                    if (!suppressResultOutputOption.isSet()) {
                        if (result instanceof Measurement[]) {
                            StringBuilder sb = new StringBuilder();
                            Measurement.getMeasurementsDescription(
                                    (Measurement[]) result, sb, 0);
                            System.out.println(sb.toString());
                        } else {
                            System.out.println(result);
                        }
                        System.out.flush();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
489069
private void processTasks() throws SQLException
   {
      //
      // Yes... we could probably read this in one query in the right order
      // using a CTE... but life's too short.
      //
      List<Row> rows = getRows("select * from zscheduleitem where zproject=? and zparentactivity_ is null and z_ent=? order by zorderinparentactivity", m_projectID, m_entityMap.get("Activity"));
      for (Row row : rows)
      {
         Task task = m_project.addTask();
         populateTask(row, task);
         processChildTasks(task);
      }
   }
1366067
public void setTaskInstanceGroups(Long taskInstId, String[] groups)
            throws DataAccessException {
        try {
            db.openConnection();
            // get group IDs
            StringBuffer sb = new StringBuffer();
            sb.append("select USER_GROUP_ID from USER_GROUP where GROUP_NAME in (");
            for (int i=0; i<groups.length; i++) {
                if (i>0) sb.append(",");
                sb.append("'").append(groups[i]).append("'");
            }
            sb.append(")");
            ResultSet rs = db.runSelect(sb.toString());
            List<Long> groupIds = new ArrayList<Long>();
            while (rs.next()) {
                groupIds.add(rs.getLong(1));
            }
            // delete existing groups
            String query = "";
            if (db.isMySQL())
                query = "delete TG1 from TASK_INST_GRP_MAPP TG1 join TASK_INST_GRP_MAPP TG2 " +
                        "using (TASK_INSTANCE_ID, USER_GROUP_ID) " +
                        "where TG2.TASK_INSTANCE_ID=?";
            else
                query = "delete from TASK_INST_GRP_MAPP where TASK_INSTANCE_ID=?";
            db.runUpdate(query, taskInstId);
            if (db.isMySQL()) db.commit(); // MySQL will lock even when no rows were deleted and using unique index, so commit so that multiple session inserts aren't deadlocked
            // insert groups
            query = "insert into TASK_INST_GRP_MAPP " +
                    "(TASK_INSTANCE_ID,USER_GROUP_ID,CREATE_DT) values (?,?," + now() + ")";
            db.prepareStatement(query);
            Object[] args = new Object[2];
            args[0] = taskInstId;
            for (Long group : groupIds) {
                args[1] = group;
                db.runUpdateWithPreparedStatement(args);
            }
            db.commit();
        } catch (Exception e) {
            db.rollback();
            throw new DataAccessException(0,"failed to associate task instance groups", e);
        } finally {
            db.closeConnection();
        }
    }
566770
public TaskMetricGroup addTask(
			final JobVertexID jobVertexId,
			final ExecutionAttemptID executionAttemptID,
			final String taskName,
			final int subtaskIndex,
			final int attemptNumber) {
		checkNotNull(jobVertexId);
		checkNotNull(executionAttemptID);
		checkNotNull(taskName);

		synchronized (this) {
			if (!isClosed()) {
				TaskMetricGroup prior = tasks.get(executionAttemptID);
				if (prior != null) {
					return prior;
				} else {
					TaskMetricGroup task = new TaskMetricGroup(
						registry,
						this,
						jobVertexId,
						executionAttemptID,
						taskName,
						subtaskIndex,
						attemptNumber);
					tasks.put(executionAttemptID, task);
					return task;
				}
			} else {
				return null;
			}
		}
	}
869730
def _execute_task_group(self, queue, tasks, all_task_ids, queue_lock):
        
        log = self.log.bind(queue=queue)

        locks = []
        # Keep track of the acquired locks: If two tasks in the list require
        # the same lock we only acquire it once.
        lock_ids = set()

        ready_tasks = []
        for task in tasks:
            if task.lock:
                if task.lock_key:
                    kwargs = task.kwargs
                    lock_id = gen_unique_id(
                        task.serialized_func,
                        None,
                        {key: kwargs.get(key) for key in task.lock_key},
                    )
                else:
                    lock_id = gen_unique_id(
                        task.serialized_func,
                        task.args,
                        task.kwargs,
                    )

                if lock_id not in lock_ids:
                    lock = Lock(self.connection, self._key('lock', lock_id), timeout=self.config['ACTIVE_TASK_UPDATE_TIMEOUT'])

                    acquired = lock.acquire(blocking=False)
                    if acquired:
                        lock_ids.add(lock_id)
                        locks.append(lock)
                    else:
                        log.info('could not acquire lock', task_id=task.id)

                        # Reschedule the task (but if the task is already
                        # scheduled in case of a unique task, don't prolong
                        # the schedule date).
                        when = time.time() + self.config['LOCK_RETRY']
                        task._move(from_state=ACTIVE, to_state=SCHEDULED,
                                   when=when, mode='min')
                        # Make sure to remove it from this list so we don't
                        # re-add to the ACTIVE queue by updating the heartbeat.
                        all_task_ids.remove(task.id)
                        continue

            ready_tasks.append(task)

        if not ready_tasks:
            return True, []

        if self.stats_thread:
            self.stats_thread.report_task_start()
        success = self._execute(queue, ready_tasks, log, locks, queue_lock, all_task_ids)
        if self.stats_thread:
            self.stats_thread.report_task_end()

        for lock in locks:
            lock.release()

        return success, ready_tasks
521088
private void postProcessTasks()
   {
      List<Task> allTasks = m_file.getTasks();
      if (allTasks.size() > 1)
      {
         Collections.sort(allTasks);

         int taskID = -1;
         int lastTaskID = -1;

         for (int i = 0; i < allTasks.size(); i++)
         {
            Task task = allTasks.get(i);
            taskID = NumberHelper.getInt(task.getID());
            // In Project the tasks IDs are always contiguous so we can spot invalid tasks by making sure all
            // IDs are represented.
            if (!task.getNull() && lastTaskID != -1 && taskID > lastTaskID + 1)
            {
               // This task looks to be invalid.
               task.setNull(true);
            }
            else
            {
               lastTaskID = taskID;
            }
         }
      }
   }
1018650
private void handleWorkItemHandlerException(ProcessWorkItemHandlerException handlerException, WorkItem workItem) {
        Map<String, Object> parameters = new HashMap<>();
        
        parameters.put("DeploymentId", workItem.getDeploymentId());
        parameters.put("ProcessInstanceId", workItem.getProcessInstanceId());
        parameters.put("WorkItemId", workItem.getId());
        parameters.put("NodeInstanceId", this.getId());
        parameters.put("ErrorMessage", handlerException.getMessage());        
        parameters.put("Error", handlerException);  
        
        // add all parameters of the work item to the newly started process instance
        parameters.putAll(workItem.getParameters());
        
        KieRuntime kruntime = getKieRuntimeForSubprocess();       
                
        ProcessInstance processInstance = ( ProcessInstance ) kruntime.createProcessInstance(handlerException.getProcessId(), parameters);
        
        this.exceptionHandlingProcessInstanceId = processInstance.getId(); 
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentProcessInstanceId", getProcessInstance().getId());
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentNodeInstanceId", getUniqueId());
        
        ((ProcessInstanceImpl) processInstance).setParentProcessInstanceId(getProcessInstance().getId());
        ((ProcessInstanceImpl) processInstance).setSignalCompletion(true);

        kruntime.startProcessInstance(processInstance.getId());
        if (processInstance.getState() == ProcessInstance.STATE_COMPLETED
                || processInstance.getState() == ProcessInstance.STATE_ABORTED) {
            exceptionHandlingCompleted(processInstance, handlerException);
        } else {
            addExceptionProcessListener();
        }
    }
582623
def _execute_handling(self, *eopatches, **kwargs):
        
        self.private_task_config.start_time = datetime.datetime.now()

        caught_exception = None
        try:
            return_value = self.execute(*eopatches, **kwargs)
        except BaseException as exception:
            caught_exception = exception, sys.exc_info()[2]

        if caught_exception is not None:  # Exception is not raised in except statement to prevent duplicated traceback
            exception, traceback = caught_exception
            raise type(exception)('During execution of task {}: {}'.format(self.__class__.__name__,
                                                                           exception)).with_traceback(traceback)

        self.private_task_config.end_time = datetime.datetime.now()
        return return_value
735032
public static void executeIn(ClassLoader loader, Runnable task) throws Exception
   {
      if (task == null)
         return;

      if (log.isLoggable(Level.FINE))
      {
         log.fine("ClassLoader [" + loader + "] task began.");
      }
      ClassLoader original = SecurityActions.getContextClassLoader();
      try
      {
         SecurityActions.setContextClassLoader(loader);
         task.run();
      }
      finally
      {
         SecurityActions.setContextClassLoader(original);
         if (log.isLoggable(Level.FINE))
         {
            log.fine("ClassLoader [" + loader + "] task ended.");
         }
      }
   }
1178580
@Override
    String execute(final Task task) {
        if (Config.DEBUG) {
            Log.v(TAG, "execute() task=" + task);
        }
        checkExecutor();
        assert task != null;
        final ITaskRunnable runnable = TaskFactory.createRunnable(task);
        final String group = task.getGroup();
        final String name = task.getName();
        addToRunnableMap(name, runnable);
        addToGroupMap(name, group);

        runnable.setFuture(mExecutor.submit(runnable));
        return name;
    }