Java Code Examples for org.flowable.engine.impl.util.CommandContextUtil#getTimerJobService()

The following examples show how to use org.flowable.engine.impl.util.CommandContextUtil#getTimerJobService() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSetProcessDefinitionStateCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void createTimerForDelayedExecution(CommandContext commandContext, List<ProcessDefinitionEntity> processDefinitions) {
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {

        if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext))
            continue;

        TimerJobService timerJobService = CommandContextUtil.getTimerJobService(commandContext);
        TimerJobEntity timer = timerJobService.createTimerJob();
        timer.setJobType(JobEntity.JOB_TYPE_TIMER);
        timer.setProcessDefinitionId(processDefinition.getId());

        // Inherit tenant identifier (if applicable)
        if (processDefinition.getTenantId() != null) {
            timer.setTenantId(processDefinition.getTenantId());
        }

        timer.setDuedate(executionDate);
        timer.setJobHandlerType(getDelayedExecutionJobHandlerType());
        timer.setJobHandlerConfiguration(TimerChangeProcessDefinitionSuspensionStateJobHandler.createJobHandlerConfiguration(includeProcessInstances));
        timerJobService.scheduleTimerJob(timer);
    }
}
 
Example 2
Source File: DeploymentEntityManagerImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void removeTimerStartJobs(ProcessDefinition processDefinition) {
    TimerJobService timerJobService = CommandContextUtil.getTimerJobService();
    List<TimerJobEntity> timerStartJobs = timerJobService.findJobsByTypeAndProcessDefinitionId(TimerStartEventJobHandler.TYPE, processDefinition.getId());
    if (timerStartJobs != null && timerStartJobs.size() > 0) {
        for (TimerJobEntity timerStartJob : timerStartJobs) {
            if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
                getEventDispatcher().dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, timerStartJob, null, null, processDefinition.getId()));
            }

            timerJobService.deleteTimerJob(timerStartJob);
        }
    }
}
 
Example 3
Source File: HandleHistoryCleanupTimerJobCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(CommandContext commandContext) {
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
    ManagementService managementService = processEngineConfiguration.getManagementService();
    TimerJobService timerJobService = CommandContextUtil.getTimerJobService(commandContext);
    List<Job> cleanupJobs = managementService.createTimerJobQuery().handlerType(BpmnHistoryCleanupJobHandler.TYPE).list();
    
    if (cleanupJobs.isEmpty()) {
        TimerJobEntity timerJob = timerJobService.createTimerJob();
        timerJob.setJobType(JobEntity.JOB_TYPE_TIMER);
        timerJob.setRevision(1);
        timerJob.setJobHandlerType(BpmnHistoryCleanupJobHandler.TYPE);
        
        BusinessCalendar businessCalendar = processEngineConfiguration.getBusinessCalendarManager().getBusinessCalendar(CycleBusinessCalendar.NAME);
        timerJob.setDuedate(businessCalendar.resolveDuedate(processEngineConfiguration.getHistoryCleaningTimeCycleConfig()));
        timerJob.setRepeat(processEngineConfiguration.getHistoryCleaningTimeCycleConfig());
        
        timerJobService.scheduleTimerJob(timerJob);
        
    } else {
        if (cleanupJobs.size() > 1) {
            for (int i = 1; i < cleanupJobs.size(); i++) {
                managementService.deleteTimerJob(cleanupJobs.get(i).getId());
            }
        }
    }

    return null;
}
 
Example 4
Source File: TimerManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void scheduleTimers(ProcessDefinitionEntity processDefinition, Process process) {
    TimerJobService timerJobService = CommandContextUtil.getTimerJobService();
    List<TimerJobEntity> timers = getTimerDeclarations(processDefinition, process);
    for (TimerJobEntity timer : timers) {
        timerJobService.scheduleTimerJob(timer);
    }
}
 
Example 5
Source File: ProcessInstanceMigrationManagerImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public Batch batchMigrateProcessInstancesOfProcessDefinition(String sourceProcDefId, ProcessInstanceMigrationDocument document, CommandContext commandContext) {
    // Check of the target definition exists before submitting the batch
    ProcessDefinition targetProcessDefinition = resolveProcessDefinition(document, commandContext);

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    List<ProcessInstance> processInstances = executionEntityManager.findProcessInstanceByQueryCriteria( new ProcessInstanceQueryImpl().processDefinitionId(sourceProcDefId));

    BatchService batchService = CommandContextUtil.getBatchService(commandContext);
    Batch batch = batchService.createBatchBuilder().batchType(Batch.PROCESS_MIGRATION_TYPE)
        .searchKey(sourceProcDefId)
        .searchKey2(targetProcessDefinition.getId())
        .status(ProcessInstanceBatchMigrationResult.STATUS_IN_PROGRESS)
        .batchDocumentJson(document.asJsonString())
        .create();
    
    JobService jobService = CommandContextUtil.getJobService(commandContext);
    for (ProcessInstance processInstance : processInstances) {
        BatchPart batchPart = batchService.createBatchPart(batch, ProcessInstanceBatchMigrationResult.STATUS_WAITING, 
                        processInstance.getId(), null, ScopeTypes.BPMN);
        
        JobEntity job = jobService.createJob();
        job.setJobHandlerType(ProcessInstanceMigrationJobHandler.TYPE);
        job.setProcessInstanceId(processInstance.getId());
        job.setJobHandlerConfiguration(ProcessInstanceMigrationJobHandler.getHandlerCfgForBatchPartId(batchPart.getId()));
        jobService.createAsyncJob(job, false);
        jobService.scheduleAsyncJob(job);
    }
    
    if (!processInstances.isEmpty()) {
        TimerJobService timerJobService = CommandContextUtil.getTimerJobService(commandContext);
        TimerJobEntity timerJob = timerJobService.createTimerJob();
        timerJob.setJobType(JobEntity.JOB_TYPE_TIMER);
        timerJob.setRevision(1);
        timerJob.setJobHandlerType(ProcessInstanceMigrationStatusJobHandler.TYPE);
        timerJob.setJobHandlerConfiguration(ProcessInstanceMigrationJobHandler.getHandlerCfgForBatchId(batch.getId()));
        
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        BusinessCalendar businessCalendar = processEngineConfiguration.getBusinessCalendarManager().getBusinessCalendar(CycleBusinessCalendar.NAME);
        timerJob.setDuedate(businessCalendar.resolveDuedate(processEngineConfiguration.getBatchStatusTimeCycleConfig()));
        timerJob.setRepeat(processEngineConfiguration.getBatchStatusTimeCycleConfig());
        
        timerJobService.scheduleTimerJob(timerJob);
    }

    return batch;
}
 
Example 6
Source File: AbstractSetProcessInstanceStateCmd.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public Void execute(CommandContext commandContext) {

    if (processInstanceId == null) {
        throw new FlowableIllegalArgumentException("ProcessInstanceId cannot be null.");
    }

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity executionEntity = executionEntityManager.findById(processInstanceId);

    if (executionEntity == null) {
        throw new FlowableObjectNotFoundException("Cannot find processInstance for id '" + processInstanceId + "'.", Execution.class);
    }
    if (!executionEntity.isProcessInstanceType()) {
        throw new FlowableException("Cannot set suspension state for execution '" + processInstanceId + "': not a process instance.");
    }

    if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, executionEntity.getProcessDefinitionId())) {
        if (getNewState() == SuspensionState.ACTIVE) {
            CommandContextUtil.getProcessEngineConfiguration().getFlowable5CompatibilityHandler().activateProcessInstance(processInstanceId);
        } else {
            CommandContextUtil.getProcessEngineConfiguration().getFlowable5CompatibilityHandler().suspendProcessInstance(processInstanceId);
        }
        return null;
    }

    SuspensionStateUtil.setSuspensionState(executionEntity, getNewState());
    executionEntityManager.update(executionEntity, false);

    // All child executions are suspended
    Collection<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstanceId);
    for (ExecutionEntity childExecution : childExecutions) {
        if (!childExecution.getId().equals(processInstanceId)) {
            SuspensionStateUtil.setSuspensionState(childExecution, getNewState());
            executionEntityManager.update(childExecution, false);
        }
    }

    // All tasks are suspended
    List<TaskEntity> tasks = CommandContextUtil.getTaskService().findTasksByProcessInstanceId(processInstanceId);
    for (TaskEntity taskEntity : tasks) {
        SuspensionStateUtil.setSuspensionState(taskEntity, getNewState());
        CommandContextUtil.getTaskService().updateTask(taskEntity, false);
    }

    // All jobs are suspended
    JobService jobService = CommandContextUtil.getJobService(commandContext);
    if (getNewState() == SuspensionState.ACTIVE) {
        List<SuspendedJobEntity> suspendedJobs = jobService.findSuspendedJobsByProcessInstanceId(processInstanceId);
        for (SuspendedJobEntity suspendedJob : suspendedJobs) {
            jobService.activateSuspendedJob(suspendedJob);
        }

    } else {
        TimerJobService timerJobService = CommandContextUtil.getTimerJobService(commandContext);
        List<TimerJobEntity> timerJobs = timerJobService.findTimerJobsByProcessInstanceId(processInstanceId);
        for (TimerJobEntity timerJob : timerJobs) {
            jobService.moveJobToSuspendedJob(timerJob);
        }

        List<JobEntity> jobs = jobService.findJobsByProcessInstanceId(processInstanceId);
        for (JobEntity job : jobs) {
            jobService.moveJobToSuspendedJob(job);
        }

        List<ExternalWorkerJobEntity> externalWorkerJobs = CommandContextUtil.getJobServiceConfiguration(commandContext)
                .getExternalWorkerJobEntityManager()
                .findJobsByProcessInstanceId(processInstanceId);

        for (ExternalWorkerJobEntity externalWorkerJob : externalWorkerJobs) {
            jobService.moveJobToSuspendedJob(externalWorkerJob);
        }

    }

    return null;
}
 
Example 7
Source File: JobRetryCmd.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public Object execute(CommandContext commandContext) {
    JobService jobService = CommandContextUtil.getJobService(commandContext);
    TimerJobService timerJobService = CommandContextUtil.getTimerJobService(commandContext);
    
    JobEntity job = jobService.findJobById(jobId);
    if (job == null) {
        return null;
    }

    ProcessEngineConfiguration processEngineConfig = CommandContextUtil.getProcessEngineConfiguration(commandContext);

    ExecutionEntity executionEntity = fetchExecutionEntity(commandContext, job.getExecutionId());
    FlowElement currentFlowElement = executionEntity != null ? executionEntity.getCurrentFlowElement() : null;
    if (executionEntity != null) {
        executionEntity.setActive(false);
    }

    String failedJobRetryTimeCycleValue = null;
    if (currentFlowElement instanceof ServiceTask) {
        failedJobRetryTimeCycleValue = ((ServiceTask) currentFlowElement).getFailedJobRetryTimeCycleValue();
    }

    AbstractRuntimeJobEntity newJobEntity = null;
    if (currentFlowElement == null || failedJobRetryTimeCycleValue == null) {

        LOGGER.debug("activity or FailedJobRetryTimerCycleValue is null in job {}. Only decrementing retries.", jobId);

        if (job.getRetries() <= 1) {
            newJobEntity = jobService.moveJobToDeadLetterJob(job);
        } else {
            newJobEntity = timerJobService.moveJobToTimerJob(job);
        }

        newJobEntity.setRetries(job.getRetries() - 1);
        if (job.getDuedate() == null || JobEntity.JOB_TYPE_MESSAGE.equals(job.getJobType())) {
            // add wait time for failed async job
            newJobEntity.setDuedate(calculateDueDate(commandContext, processEngineConfig.getAsyncFailedJobWaitTime(), null));
        } else {
            // add default wait time for failed job
            newJobEntity.setDuedate(calculateDueDate(commandContext, processEngineConfig.getDefaultFailedJobWaitTime(), job.getDuedate()));
        }

    } else {
        try {
            DurationHelper durationHelper = new DurationHelper(failedJobRetryTimeCycleValue, processEngineConfig.getClock());
            int jobRetries = job.getRetries();
            if (job.getExceptionMessage() == null) {
                // change default retries to the ones configured
                jobRetries = durationHelper.getTimes();
            }

            if (jobRetries <= 1) {
                newJobEntity = jobService.moveJobToDeadLetterJob(job);
            } else {
                newJobEntity = timerJobService.moveJobToTimerJob(job);
            }

            newJobEntity.setDuedate(durationHelper.getDateAfter());

            if (job.getExceptionMessage() == null) { // is it the first exception
                LOGGER.debug("Applying JobRetryStrategy '{}' the first time for job {} with {} retries", failedJobRetryTimeCycleValue, job.getId(), durationHelper.getTimes());

            } else {
                LOGGER.debug("Decrementing retries of JobRetryStrategy '{}' for job {}", failedJobRetryTimeCycleValue, job.getId());
            }

            newJobEntity.setRetries(jobRetries - 1);

        } catch (Exception e) {
            throw new FlowableException("failedJobRetryTimeCycle has wrong format:" + failedJobRetryTimeCycleValue, exception);
        }
    }

    if (exception != null) {
        newJobEntity.setExceptionMessage(exception.getMessage());
        newJobEntity.setExceptionStacktrace(getExceptionStacktrace());
    }

    // Dispatch both an update and a retry-decrement event
    FlowableEventDispatcher eventDispatcher = CommandContextUtil.getEventDispatcher();
    if (eventDispatcher != null && eventDispatcher.isEnabled()) {
        eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, newJobEntity));
        eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_RETRIES_DECREMENTED, newJobEntity));
    }

    return null;
}