Runs a task in the background, returning a job handle which can be used
to get the status of the running task.

@param string $functionName
@param string $workload
@param string $unique

@return Task
194277
public function doLowBackground($functionName, $workload, $unique = null)
    {
        $set = $this->createSet($functionName, $workload, $unique, Task::JOB_LOW_BACKGROUND);
        $this->runSet($set);

        return current($set->tasks);
    }
1073252
public function runDelayed($jobId, \Closure $runCallback)
    {
        $job = $this->jobProcessor->findJobById($jobId);
        if (! $job) {
            throw JobNotFoundException::create($jobId);
        }
        $this->throwIfJobIsStale($job);

        if ($job->getRootJob()->isInterrupted()) {
            if (! $job->getStoppedAt()) {
                $this->jobProcessor->cancelChildJob($job);
            }

            return null;
        }

        $this->jobExtension->onPreRunDelayed($job);

        if ($this->isReadyForStart($job)) {
            $this->jobProcessor->startChildJob($job);
        }

        $result = $this->callbackResult($runCallback, $job);

        if (! $job->getStoppedAt()) {
            $result
                ? $this->jobProcessor->successChildJob($job)
                : $this->jobProcessor->failChildJob($job);
        }

        $this->jobExtension->onPostRunDelayed($job, $result);

        return $result;
    }
1209344
public function executeOnce(\Closure $task)
    {
        $isBlocked = $this->checkedLock();
        $error = null;
        try {
            if (! $isBlocked) {
                call_user_func($task);

            }
        } catch (\Exception $e) {
            $error = $e;

        }
        $this->unlock();
        if (! is_null($error)) {
            throw $error;

        }
    }
602120
public static function task($data, $worker_id = -1, $callback = null) {
		if ($callback === true) {
			return self::$server->taskCo([$data]);
		} elseif (is_callable($callback)) {
			self::$server->task($data, $worker_id, $callback);
		} else {
			self::$server->task($data, $worker_id);
		}
	}
440031
public function perform(WorkflowEngine $workflowEngine, WorkflowMessage $workflowMessage = null)
    {
        $taskListEntry = $this->taskList->getNextNotStartedTaskListEntry();

        if (is_null($taskListEntry)) {
            throw new \RuntimeException('ChunkProcess::perform was called but there are no tasks configured!');
        }

        if (is_null($workflowMessage)) {
            $this->recordThat(TaskEntryMarkedAsRunning::at($taskListEntry->taskListPosition()));
            $this->receiveMessage(
                LogMessage::logNoMessageReceivedFor($taskListEntry->task(), $taskListEntry->taskListPosition()),
                $workflowEngine
            );
            return;
        }

        $workflowMessage = $workflowMessage->reconnectToProcessTask($taskListEntry->taskListPosition());

        if (count($this->taskList->getAllTaskListEntries()) > 1) {
            $this->recordThat(TaskEntryMarkedAsRunning::at($taskListEntry->taskListPosition()));
            $this->logErrorMsg(
                'The ChunkProcess can only handle a single RunSubProcess task but there are more tasks configured',
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        if (! $taskListEntry->task() instanceof RunSubProcess) {
            $this->recordThat(TaskEntryMarkedAsRunning::at($taskListEntry->taskListPosition()));
            $this->logErrorMsg(
                sprintf(
                    'The ChunkProcess can only handle a RunSubProcess task but there is a %s task configured',
                    get_class($taskListEntry->task())
                ),
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        if (! MessageNameUtils::isProcessingEvent($workflowMessage->messageName())) {
            $this->recordThat(TaskEntryMarkedAsRunning::at($taskListEntry->taskListPosition()));
            $this->receiveMessage(
                LogMessage::logWrongMessageReceivedFor($taskListEntry->task(), $taskListEntry->taskListPosition(), $workflowMessage),
                $workflowEngine
            );
            return;
        }

        $collection = $workflowMessage->payload()->toType();

        if (! $collection instanceof CollectionType) {
            $this->logErrorMsg(
                sprintf(
                    'The ChunkProcess requires a Prooph\ProcessingType\CollectionType as payload of the incoming message, but it is a %s type given',
                    $workflowMessage->payload()->getTypeClass()
                ),
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        $metadata = $workflowMessage->metadata();

        if (! isset($metadata[self::META_OFFSET])) {
            $this->logErrorMsg(
                'The ChunkProcess requires a offset key in the message metadata.',
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        if ((int)$metadata[self::META_OFFSET] !== 0) {
            $this->logErrorMsg(
                'The ChunkProcess requires that the first chunk starts with a offset of 0.',
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        if (! isset($metadata[self::META_LIMIT])) {
            $this->logErrorMsg(
                'The ChunkProcess requires a limit key in the message metadata.',
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        if ((int)$metadata[self::META_LIMIT] <= 0) {
            $this->logErrorMsg(
                'The ChunkProcess requires that metadata.limit is greater than 0.',
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        if (! isset($metadata[self::META_TOTAL_ITEMS])) {
            $this->logErrorMsg(
                'The ChunkProcess requires a total_items key in the message metadata.',
                $workflowMessage,
                $workflowEngine
            );
            return;
        }

        $this->startSubProcessForEachChunk($workflowMessage, $workflowEngine);
    }
383759
function handleInternalRequest( $functionName, $params, $server=null )
    {
        if ( $server === null )
        {
            $server = $this;
        }
        switch( $functionName )
        {
            case 'system.listMethods':
                if ( count( $params ) != 0 )
                {
                    return new ggWebservicesFault( self::INVALIDPARAMSERROR, self::INVALIDPARAMSSTRING );
                }
                return $server->registeredMethods();

            case 'system.methodSignature':
                if ( count( $params ) != 1 || !is_string( $params[0] ) )
                {
                    return new ggWebservicesFault( self::INVALIDPARAMSERROR, self::INVALIDPARAMSSTRING );
                }
                if ( in_array( $params[0], $server->internalMethods ) )
                {
                    switch( $params[0] )
                    {
                        case 'system.listMethods':
                            return array( array( 'array' ) );
                        case 'system.methodSignature':
                            return array( array( 'array', 'string' ) );
                        case 'system.methodHelp':
                            return array( array( 'string', 'string' ) );
                        case 'system.multicall':
                            return array( array( 'array', 'array' ) );
                    }
                }
                if ( !array_key_exists( $params[0], $server->FunctionList ) )
                {
                    return new ggWebservicesFault( self::INVALIDINTROSPECTIONERROR, self::INVALIDINTROSPECTIONSTRING );
                }
                $results = array();
                foreach( $server->FunctionList[$params[0]] as $syntax )
                {
                    if ( $syntax['in'] !== null )
                    {
                        $syntax['in'] = array_values( $syntax['in'] );
                        array_unshift( $syntax['in'], $syntax['out'] );
                        $results[] = $syntax['in'];
                    }
                }
                return $results;

            case 'system.methodHelp':
                if ( count( $params ) != 1 || !is_string( $params[0] ) )
                {
                    return new ggWebservicesFault( self::INVALIDPARAMSERROR, self::INVALIDPARAMSSTRING );
                }
                if ( in_array( $params[0], $server->internalMethods ) )
                {
                    switch( $params[0] )
                    {
                        case 'system.listMethods':
                            return 'This method lists all the methods that the server knows how to dispatch';
                        case 'system.methodSignature':
                            return 'Returns an array of known signatures (an array of arrays) for the method name passed. First member of each array is the return type';
                        case 'system.methodHelp':
                            return 'Returns help text if defined for the method passed, otherwise returns an empty string';
                        case 'system.multicall':
                            return 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details';
                    }
                }
                if ( !array_key_exists( $params[0], $server->FunctionDescription ) )
                {
                    return new ggWebservicesFault( self::INVALIDINTROSPECTIONERROR, self::INVALIDINTROSPECTIONSTRING );
                }
                return $server->FunctionDescription[$params[0]];

            case 'system.multicall':
                // validate first the multicall syntax
                if ( count( $params ) != 1 || !is_array( $params[0] ) )
                {
                    return new ggWebservicesFault( self::INVALIDPARAMSERROR, self::INVALIDPARAMSSTRING );
                }
                foreach( $params[0] as $request )
                {
                    if ( !is_array( $request ) || //count( $request ) != 2 ||
                         !array_key_exists( 'methodName', $request) || !is_string( $request['methodName'] )||
                         !array_key_exists( 'params', $request ) || !is_array( $request['params'] ) )
                    {
                        return new ggWebservicesFault( self::INVALIDPARAMSERROR, self::INVALIDPARAMSSTRING );
                    }
                }
                // then execute all methods
                $results = array();
                foreach( $params[0] as $request)
                {
                    $resp = $server->handleRequest( $request['methodName'], $request['params'] );
                    if ( is_a( $resp, 'ggWebservicesFault' ) )
                    {
                        $results[] = array( 'faultCode' => $resp->faultCode(), 'faultString' => $resp->faultString() );
                    }
                    else
                    {
                        $results[] = $resp;
                    }
                }
                return $results;
            default:
                return parent::handleInternalRequest( $functionName, $params );
        }
    }
531660
def runDynTask(task):
    '''
    

    '''
    func = getDynLocal(task[0])
    if func is None:
        raise s_exc.NoSuchFunc(name=task[0])
    return func(*task[1], **task[2])
982334
static function runTrigger( $name, $moduleName, $function, $parameters, $keys = null )
    {
        $trigger = eZPersistentObject::fetchObject( eZTrigger::definition(),
                                                    null,
                                                    array( 'name' => $name,
                                                           'module_name' => $moduleName,
                                                           'function_name' => $function ),
                                                    true );
        if ( $trigger !== NULL )
        {
            $workflowID = $trigger->attribute( 'workflow_id' );
            $workflow = eZWorkflow::fetch( $workflowID );
            if ( $keys != null )
            {
                $keys[] = 'workflow_id';
            }

            $parameters['workflow_id']     = $workflowID;
            $parameters['trigger_name']    = $name;
            $parameters['module_name']     = $moduleName;
            $parameters['module_function'] = $function;
            // It is very important that the user_id is set correctly.
            // If it was not supplied by the calling code we will use
            // the currently logged in user.
            if ( !isset( $parameters['user_id'] ) or
                 $parameters['user_id'] == 0 )
            {
                $user = eZUser::currentUser();
                $parameters['user_id'] = $user->attribute( 'contentobject_id' );
            }
            $processKey = eZWorkflowProcess::createKey( $parameters, $keys );

//            $searchKey = eZWorkflowProcess::createKey( $keyArray );

            $workflowProcessList = eZWorkflowProcess::fetchListByKey( $processKey );

            if ( count( $workflowProcessList ) > 0 )
            {
                $existingWorkflowProcess = $workflowProcessList[0];
                $existingWorkflowStatus = $existingWorkflowProcess->attribute( 'status' );


                switch( $existingWorkflowStatus )
                {
                    case eZWorkflow::STATUS_FAILED:
                    case eZWorkflow::STATUS_CANCELLED:
                    case eZWorkflow::STATUS_NONE:
                    case eZWorkflow::STATUS_BUSY:
                    {
                        $existingWorkflowProcess->removeThis();
                        return array( 'Status' => eZTrigger::WORKFLOW_CANCELLED,
                                      'Result' => null );
                    } break;
                    case eZWorkflow::STATUS_FETCH_TEMPLATE:
                    case eZWorkflow::STATUS_FETCH_TEMPLATE_REPEAT:
                    case eZWorkflow::STATUS_REDIRECT:
                    case eZWorkflow::STATUS_RESET:
                    {
                        return eZTrigger::runWorkflow( $existingWorkflowProcess );
//                        return eZTrigger::FETCH_TEMPLATE;
                    } break;
                    case eZWorkflow::STATUS_DEFERRED_TO_CRON:
                    {
                        return eZTrigger::runWorkflow( $existingWorkflowProcess );
/*                        return array( 'Status' => eZTrigger::STATUS_CRON_JOB,

                                      'Result' => array( 'content' => 'Operation halted during execution.<br/>Refresh page to continue<br/><br/><b>Note: The halt is just a temporary test</b><br/>',
                                                         'path' => array( array( 'text' => 'Operation halt',
                                                                            'url' => false ) ) ) );
*/                  } break;
                    case eZWorkflow::STATUS_DONE:
                    {
                        $existingWorkflowProcess->removeThis();
                        return array( 'Status' => eZTrigger::WORKFLOW_DONE,
                                      'Result' => null );
                    }
                }
                return array( 'Status' => eZTrigger::WORKFLOW_CANCELLED,
                              'Result' => null );
            }else
            {
//                print( "\n starting new workflow process \n");
//                var_dump( $keyArray );
//                print( " $workflowID, $userID, $objectID, $version, $nodeID, \n ");
            }
            $workflowProcess = eZWorkflowProcess::create( $processKey, $parameters );

            $workflowProcess->store();

            return eZTrigger::runWorkflow( $workflowProcess );

        }
        else
        {
            return array( 'Status' => eZTrigger::NO_CONNECTED_WORKFLOWS,
                          'Result' => null );
        }
    }
133327
protected function runTask($container, $task)
    {
        $macroOptions = $container->getMacroOptions($this->argument('task'));

        $confirm = $container->getTask($task, $macroOptions)->confirm;

        if ($confirm && ! $this->confirmTaskWithUser($task, $confirm)) {
            return;
        }

        if (($exitCode = $this->runTaskOverSSH($container->getTask($task, $macroOptions))) > 0) {
            foreach ($container->getErrorCallbacks() as $callback) {
                call_user_func($callback, $task);
            }

            return $exitCode;
        }

        foreach ($container->getAfterCallbacks() as $callback) {
            call_user_func($callback, $task);
        }
    }
196196
protected function execute(callable $task)
	{
		if ($this->beingDestroyed) {
			throw new \RuntimeException(self::ERROR_BEING_DESTROY);
		}
		
		$this->taskQueue->enqueue($task);
		
		if ($this->idleQueue->isEmpty() && ($this->size + $this->beingCreatedSize) < $this->maxSize) {
			$this->newResource();
		}
		
		$this->taskDequeue();
	}
109066
public function doHighBackground($functionName, $workload, $unique = null)
    {
        $set = $this->createSet($functionName, $workload, $unique, Task::JOB_HIGH_BACKGROUND);
        $this->runSet($set);

        return current($set->tasks);
    }
160423
public function runUnique($ownerId, $name, callable $runCallback)
    {
        $rootJob = $this->jobProcessor->findOrCreateRootJob($ownerId, $name, true);
        if (!$rootJob) {
            return;
        }

        $childJob = $this->jobProcessor->findOrCreateChildJob($name, $rootJob);

        if (!$childJob->getStartedAt()) {
            $this->jobProcessor->startChildJob($childJob);
        }

        $jobRunner = new self($this->jobProcessor, $rootJob);

        try {
            $result = call_user_func($runCallback, $jobRunner, $childJob);
        } catch (\Throwable $e) {
            try {
                $this->jobProcessor->failChildJob($childJob);
            } catch (\Throwable $t) {
                throw new OrphanJobException(sprintf(
                    'Job cleanup failed. ID: "%s" Name: "%s"',
                    $childJob->getId(),
                    $childJob->getName()
                ), 0, $e);
            }

            throw $e;
        }

        if (!$childJob->getStoppedAt()) {
            $result
                ? $this->jobProcessor->successChildJob($childJob)
                : $this->jobProcessor->failChildJob($childJob);
        }

        return $result;
    }
657140
public function findOrCreateRootJob($ownerId, $jobName, $unique = false)
    {
        if (! $ownerId) {
            throw new \LogicException('OwnerId must not be empty');
        }

        if (! $jobName) {
            throw new \LogicException('Job name must not be empty');
        }

        $job = $this->jobStorage->findRootJobByOwnerIdAndJobName($ownerId, $jobName);
        if ($job) {
            return $job;
        }

        $job = $this->jobStorage->createJob();
        $job->setOwnerId($ownerId);
        $job->setStatus(Job::STATUS_NEW);
        $job->setName($jobName);
        $job->setCreatedAt(new \DateTime());
        $job->setLastActiveAt(new \DateTime());
        $job->setStartedAt(new \DateTime());
        $job->setJobProgress(0);
        $job->setUnique((bool) $unique);

        return $this->saveJobAndStaleDuplicateIfQualifies($job);
    }
1306326
public static function deliver(
        string $taskName,
        string $methodName,
        array $params = [],
        string $type = self::TYPE_CO,
        int $timeout = 3
    ) {
        if (! in_array($type, [static::TYPE_CO, static::TYPE_ASYNC], false)) {
            throw new TaskException('Invalid task type.');
        }
        $data = TaskHelper::pack($taskName, $methodName, $params, $type);
        if (! App::isWorkerStatus() && ! App::isCoContext()) {
            return static::deliverByQueue($data);
        }

        if (! App::isWorkerStatus() && App::isCoContext()) {
            throw new TaskException('Deliver in non-worker environment, please deliver the task via HTTP request.');
        }

        $server = App::$server->getServer();
        switch ($type) {
            case static::TYPE_CO:
                $tasks[0] = $data;
                $profileKey = 'task' . '.' . $taskName . '.' . $methodName;
                App::profileStart($profileKey);
                $result = $server->taskCo($tasks, $timeout);
                App::profileEnd($profileKey);
                return $result;
                break;
            case static::TYPE_ASYNC:
            default:
                // Deliver async task
                return $server->task($data);
                break;
        }
    }
220673
def _fire_ret_load_specific_fun(self, load, fun_index=0):
        '''
        
        '''
        if isinstance(load['fun'], list):
            # Multi-function job
            fun = load['fun'][fun_index]
            # 'retcode' was already validated to exist and be non-zero
            # for the given function in the caller.
            if isinstance(load['retcode'], list):
                # Multi-function ordered
                ret = load.get('return')
                if isinstance(ret, list) and len(ret) > fun_index:
                    ret = ret[fun_index]
                else:
                    ret = {}
                retcode = load['retcode'][fun_index]
            else:
                ret = load.get('return', {})
                ret = ret.get(fun, {})
                retcode = load['retcode'][fun]
        else:
            # Single-function job
            fun = load['fun']
            ret = load.get('return', {})
            retcode = load['retcode']

        try:
            for tag, data in six.iteritems(ret):
                data['retcode'] = retcode
                tags = tag.split('_|-')
                if data.get('result') is False:
                    self.fire_event(
                        data,
                        '{0}.{1}'.format(tags[0], tags[-1])
                    )  # old dup event
                    data['jid'] = load['jid']
                    data['id'] = load['id']
                    data['success'] = False
                    data['return'] = 'Error: {0}.{1}'.format(
                        tags[0], tags[-1])
                    data['fun'] = fun
                    data['user'] = load['user']
                    self.fire_event(
                        data,
                        tagify([load['jid'],
                                'sub',
                                load['id'],
                                'error',
                                fun],
                               'job'))
        except Exception:
            pass
394978
public function runTask($task, $args = array())
    {
        $wf = $this->getWorkflowObject();
        if (in_array($task, $wf->getAllowedTasks())) {
            $wpr = call_user_func_array(array($wf, $task), array($this, $args));
            $this->updateOnAction($wf);
        }
        if (!($wpr instanceof Response)) {
            $wpr = new Response();
        }

        $event = new GenericEvent();
        $event->setArgument('response', $wpr);

        Events::dispatch('workflow_progressed', $event);

        return $wpr;
    }
1000888
public static function createProcess($task): Runnable
    {
        if (! self::$isInitialised) {
            self::init();
        }

        if (! Pool::isSupported()) {
            return SynchronousProcess::create($task, self::getId());
        }

        $process = new Process(implode(' ', [
            'exec php',
            self::$childProcessScript,
            self::$autoloader,
            self::encodeTask($task),
        ]));

        return ParallelProcess::create($process, self::getId());
    }