execute service process using asynch engine
550735
private ProcessInstance executeServiceProcess(ProcessExecutor engine, Long processId,
            String ownerType, Long ownerId, String masterRequestId, Map<String,String> parameters,
            String secondaryOwnerType, Long secondaryOwnerId, Map<String,String> headers) throws Exception {
        Process procdef = getProcessDefinition(processId);
        Long startActivityId = procdef.getStartActivity().getId();
        if (masterRequestId == null)
            masterRequestId = genMasterRequestId();
        ProcessInstance mainProcessInst = engine.createProcessInstance(
                processId, ownerType, ownerId, secondaryOwnerType, secondaryOwnerId,
                masterRequestId, parameters);
        mainProcessInstanceId = mainProcessInst.getId();
        engine.updateProcessInstanceStatus(mainProcessInst.getId(), WorkStatus.STATUS_PENDING_PROCESS);
        if (OwnerType.DOCUMENT.equals(ownerType) && ownerId != 0L) {
            setOwnerDocumentProcessInstanceId(engine, ownerId, mainProcessInst.getId(), masterRequestId);
            bindRequestVariable(procdef, ownerId, engine, mainProcessInst);
        }
        if (headers != null) {
            bindRequestHeadersVariable(procdef, headers, engine, mainProcessInst);
        }
        logger.info(logtag(processId, mainProcessInst.getId(), masterRequestId),
                WorkStatus.LOGMSG_PROC_START + " - " + procdef.getQualifiedName() + "/" + procdef.getVersionString());
        engine.notifyMonitors(mainProcessInst, WorkStatus.LOGMSG_PROC_START);
        // setProcessInstanceStatus will really set to STATUS_IN_PROGRESS - hint to set START_DT as well
        InternalEvent event = InternalEvent.createActivityStartMessage(startActivityId,
                mainProcessInst.getId(), 0L, masterRequestId, EventType.EVENTNAME_START);
        InternalMessenger msgBroker = engine.getInternalMessenger();
        lastException = null;
        processEvent(engine, event, mainProcessInst);
        while ((event = msgBroker.getNextMessageFromQueue(engine)) != null) {
            ProcessInstance procInst = this.findProcessInstance(engine, event);
            processEvent(engine, event, procInst);
        }
        mainProcessInst = engine.getProcessInstance(mainProcessInst.getId());
        return mainProcessInst;
    }
1119424
def execute_greenlet_async(func, *args, **kwargs):
  
  global _GREENLET_EXECUTOR
  if _GREENLET_EXECUTOR is None:
    _GREENLET_EXECUTOR = GreenletExecutor(
      num_greenlets=settings.node.greenlet_pool_size)
  return _GREENLET_EXECUTOR.submit(func, *args, **kwargs)
1297147
function _run() {
    _verifyCWD();

    var customStartupFilePath = path.resolve(process.cwd() + '/bin/www');

    if (fs.existsSync(customStartupFilePath)) {
        require(customStartupFilePath);
    } else if (fs.existsSync(PROJECT_INDEX)) {
        let service = require(PROJECT_INDEX);
        if (!(service instanceof Service)) {
            utils._stderr(`${PROJECT_INDEX} does not export a Service object`);
            process.exit(1);
        }

        service.listen();
    }
}
717989
def _execute(self, handler, *args, **kwargs):
        
        # difference to Axel Events: we don't use a timeout and execute all handlers in same thread
        # FIXME: =>possible problem:
        #                       blocking of event firing when user gives a long- or infinitly-running callback function
        # (in Python it doesn't seem possible to forcefully kill a thread with clean ressource releasing,
        #  a thread has to cooperate und behave nice...
        #  execution and killing a process would be possible, but has data corruption problems with queues
        #  and possible interprocess communication problems with given handler/callback function)

        result = None
        exc_info = None

        try:
            result = handler(*args, **kwargs)
        except Exception:
            exc_info = sys.exc_info()
        if exc_info:
            return exc_info
        return result
1022184
function exec(cmd, args = [], silent = false) {
    return __awaiter(this, void 0, void 0, function* () {
        const response = [];
        return new Promise((resolve, reject) => {
            const exe = child_process_1.spawn(cmd, args, {
                env: process.env
            });
            exe.stdout.on('data', data => {
                response.push(data.toString());
                if (!silent) {
                    console.log(data.toString());
                }
            });
            exe.stderr.on('data', data => {
                if (!silent) {
                    console.error(data.toString());
                }
            });
            exe.on('exit', code => {
                if (code === 0) {
                    return resolve(response);
                }
                else {
                    if (!silent) {
                        console.error('Problem executing ' + cmd);
                    }
                    return reject();
                }
            });
        });
    });
}
548647
public static Object executeAsyncScript(String script, Object... args) {
        return driver().executeAsyncScript(script, args);
    }
1233101
def run_after_async(seconds, func, *args, **kwargs):
    """"""
    t = Timer(seconds, func, args, kwargs)
    t.daemon = True
    t.start()
    return t
1013431
public void execute(ProgramResponse response, int timeout) {
        ProcessBuilder builder = createProcessBuilder(response);
        invokeProgram(builder, response, timeout);
    }
1291105
public boolean execute(ProcessInstance processInstance) {
		log.debug("{}",this);
		ProcessInstanceUtils.setQueue(processInstance, getOwnerProcess().getWorkflowManager().getQueue(m_queue));
		return false;
	}
105924
async def _run(self, data_id, script):
        """"""
        self.data_id = data_id

        # Fetch data instance to get any executor requirements.
        self.process = PROCESS
        requirements = self.process['requirements']
        self.requirements = requirements.get('executor', {}).get(self.name, {})  # pylint: disable=no-member
        self.resources = requirements.get('resources', {})

        logger.debug("Preparing output files for Data with id {}".format(data_id))
        os.chdir(EXECUTOR_SETTINGS['DATA_DIR'])
        try:
            log_file = self._create_file('stdout.txt')
            json_file = self._create_file('jsonout.txt')
        except FileExistsError:
            logger.error("Stdout or jsonout out file already exists.")
            # Looks like executor was already ran for this Data object,
            # so don't raise the error to prevent setting status to error.
            await self._send_manager_command(ExecutorProtocol.ABORT, expect_reply=False)
            return

        proc_pid = await self.start()

        await self.update_data_status(
            status=DATA_META['STATUS_PROCESSING'],
            process_pid=proc_pid
        )

        # Run process and handle intermediate results
        logger.info("Running program for Data with id {}".format(data_id))
        logger.debug("The program for Data with id {} is: \n{}".format(data_id, script))
        await self.run_script(script)
        spawn_processes = []
        output = {}
        process_error, process_warning, process_info = [], [], []
        process_progress, process_rc = 0, 0

        # read process output
        try:
            stdout = self.get_stdout()
            while True:
                line = await stdout.readline()
                logger.debug("Process's output: {}".format(line.strip()))

                if not line:
                    break
                line = line.decode('utf-8')

                try:
                    if line.strip().startswith('run'):
                        # Save process and spawn if no errors
                        log_file.write(line)
                        log_file.flush()

                        for obj in iterjson(line[3:].strip()):
                            spawn_processes.append(obj)
                    elif line.strip().startswith('export'):
                        file_name = line[6:].strip()

                        export_folder = SETTINGS['FLOW_EXECUTOR']['UPLOAD_DIR']
                        unique_name = 'export_{}'.format(uuid.uuid4().hex)
                        export_path = os.path.join(export_folder, unique_name)

                        self.exported_files_mapper[self.data_id][file_name] = unique_name

                        shutil.move(file_name, export_path)
                    else:
                        # If JSON, save to MongoDB
                        updates = {}
                        for obj in iterjson(line):
                            for key, val in obj.items():
                                if key.startswith('proc.'):
                                    if key == 'proc.error':
                                        process_error.append(val)
                                        if not process_rc:
                                            process_rc = 1
                                            updates['process_rc'] = process_rc
                                        updates['process_error'] = process_error
                                        updates['status'] = DATA_META['STATUS_ERROR']
                                    elif key == 'proc.warning':
                                        process_warning.append(val)
                                        updates['process_warning'] = process_warning
                                    elif key == 'proc.info':
                                        process_info.append(val)
                                        updates['process_info'] = process_info
                                    elif key == 'proc.rc':
                                        process_rc = int(val)
                                        updates['process_rc'] = process_rc
                                        if process_rc != 0:
                                            updates['status'] = DATA_META['STATUS_ERROR']
                                    elif key == 'proc.progress':
                                        process_progress = int(float(val) * 100)
                                        updates['process_progress'] = process_progress
                                else:
                                    output[key] = val
                                    updates['output'] = output

                        if updates:
                            await self.update_data_status(**updates)
                            # Process meta fields are collected in listener, so we can clear them.
                            process_error, process_warning, process_info = [], [], []

                        if process_rc > 0:
                            log_file.close()
                            json_file.close()
                            await self._send_manager_command(ExecutorProtocol.FINISH, extra_fields={
                                ExecutorProtocol.FINISH_PROCESS_RC: process_rc
                            })
                            return

                        # Debug output
                        # Not referenced in Data object
                        json_file.write(line)
                        json_file.flush()

                except ValueError as ex:
                    # Ignore if not JSON
                    log_file.write(line)
                    log_file.flush()

        except MemoryError as ex:
            logger.error("Out of memory:\n\n{}".format(ex))

        except IOError as ex:
            # TODO: if ex.errno == 28: no more free space
            raise ex
        finally:
            # Store results
            log_file.close()
            json_file.close()

        return_code = await self.end()

        if process_rc < return_code:
            process_rc = return_code

        # send a notification to the executor listener that we're done
        finish_fields = {
            ExecutorProtocol.FINISH_PROCESS_RC: process_rc
        }
        if spawn_processes and process_rc == 0:
            finish_fields[ExecutorProtocol.FINISH_SPAWN_PROCESSES] = spawn_processes
            finish_fields[ExecutorProtocol.FINISH_EXPORTED_FILES] = self.exported_files_mapper

        return finish_fields
1147932
function executeApiCall(callback, needConnection) {
        needConnection = typeof needConnection !== 'undefined' ? needConnection : true;
        authenticate(function (error, result) {
            if (error || !result) {
                callback(error, result);
                return;
            }
            if (needConnection) {
                isConnected(function (error, result) {
                    if (error || !result) {
                        console.error("[Deluge] WebUI not connected to a daemon");
                        return;
                    }
                    callback(error, result);
                });
            } else {
                callback(error, result);
            }
        });
    }
1275141
function run() {
        var startTime = (new Date()).getTime();

        // parse the command line using the commander object
        processCommandLine();

        // leverage the middleware to initialize all our services, adapters, etc. (i.e. connect to mongo, etc.)
        mwServiceInit.init({ container: 'batch' })
            .then(function () {
                var app = pancakes.cook(casing.camelCase(commander.app) + 'Batch');
                return app.run(commander);
            })
            .then(function () {
                var endTime = (new Date()).getTime();
                var diffTime = (endTime - startTime) / 1000;
                log.info(commander.app + ' complete (' + diffTime + 's)');
                process.exit(0);
            })
            .catch(function (err) {
                log.error(err);
                process.exit(1);
            });
    }
339401
function execute(cmd) {
  var result = promise.defer();
  exec(cmd, function(err, stdout) {
    if (err) {
      result.reject(err);
    } else {
      result.fulfill(stdout);
    }
  });
  return result.promise;
}
856450
async function start(service) {
  return new Promise((resolve) => {
    const snapshotsDir = path.join(__dirname, '../../test/services/', service.name, 'snapshots');
    const app = yakbak(service.defaultUrl, {
      dirname: snapshotsDir,
      hash: customHash
    });
    const proxy = http.createServer(app).listen(service.port, () => {
      console.log(`Yakbak server listening on port ${service.port}. Proxy for ${service.defaultUrl}`);
    });

    resolve(proxy);
  });
}
1248170
function process(doc, cb) {
    freeze()
    assertParser('process', processor.Parser)
    assertCompiler('process', processor.Compiler)

    if (!cb) {
      return new Promise(executor)
    }

    executor(null, cb)

    function executor(resolve, reject) {
      var file = vfile(doc)

      pipeline.run(processor, {file: file}, done)

      function done(err) {
        if (err) {
          reject(err)
        } else if (resolve) {
          resolve(file)
        } else {
          cb(null, file)
        }
      }
    }
  }
315585
async def call(self, action, **kwargs):
        """"""
        act = self.service.action(action)
        _LOGGER.info("Calling %s with %s", action, kwargs)
        res = await act.async_call(**kwargs)

        _LOGGER.info("  Result: %s" % res)

        return res
664290
public <T> void executeAsync(Call call, ApiCallback<T> callback) {
        executeAsync(call, null, callback);
    }