/// <summary> /// /// </summary> /// <param name="job"></param> public virtual void Unacquire(IJob job) { if (job == null) { return; } // Deleting the old job and inserting it again with another id, // will avoid that the job is immediately is picked up again (for example // when doing lots of exclusive jobs for the same process instance) if (job is IJobEntity jobEntity) { processEngineConfiguration.JobEntityManager.Delete(new KeyValuePair <string, object>("id", jobEntity.Id)); IJobEntity newJobEntity = processEngineConfiguration.JobEntityManager.Create(); CopyJobInfo(newJobEntity, jobEntity); newJobEntity.Id = null; // We want a new id to be assigned to this job newJobEntity.LockExpirationTime = null; newJobEntity.LockOwner = null; processEngineConfiguration.JobEntityManager.Insert(newJobEntity); // We're not calling triggerExecutorIfNeeded here after the inser. The unacquire happened // for a reason (eg queue full or exclusive lock failure). No need to try it immediately again, // as the chance of failure will be high. } else { // It could be a v5 job, so simply unlock it. processEngineConfiguration.JobEntityManager.ResetExpiredJob(job.Id); } }
public virtual object Execute(ICommandContext commandContext) { foreach (string jobId in jobIds) { IJobEntity jobToDelete = commandContext.JobEntityManager.FindById <IJobEntity>(new KeyValuePair <string, object>("id", jobId)); if (jobToDelete != null) { // When given job doesn't exist, ignore if (commandContext.ProcessEngineConfiguration.EventDispatcher.Enabled) { commandContext.ProcessEngineConfiguration.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.JOB_CANCELED, jobToDelete)); } commandContext.JobEntityManager.Delete(jobToDelete); } else { ITimerJobEntity timerJobToDelete = commandContext.TimerJobEntityManager.FindById <ITimerJobEntity>(new KeyValuePair <string, object>("id", jobId)); if (timerJobToDelete != null) { // When given job doesn't exist, ignore if (commandContext.ProcessEngineConfiguration.EventDispatcher.Enabled) { commandContext.ProcessEngineConfiguration.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.JOB_CANCELED, timerJobToDelete)); } commandContext.TimerJobEntityManager.Delete(timerJobToDelete); } } } return(null); }
/// <summary> /// /// </summary> /// <param name="execution"></param> /// <param name="exclusive"></param> /// <returns></returns> protected internal virtual IJobEntity InternalCreateAsyncJob(IExecutionEntity execution, bool exclusive) { IJobEntity asyncJob = processEngineConfiguration.JobEntityManager.Create(); FillDefaultAsyncJobInfo(asyncJob, execution, exclusive); return(asyncJob); }
protected internal virtual void SendCancelEvent(IJobEntity jobToDelete) { if (Context.ProcessEngineConfiguration.EventDispatcher.Enabled) { Context.ProcessEngineConfiguration.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.JOB_CANCELED, jobToDelete)); } }
protected internal virtual IJobEntity GetJobToDelete(ICommandContext commandContext) { if (jobId is null) { throw new ActivitiIllegalArgumentException("jobId is null"); } if (log.IsEnabled(LogLevel.Debug)) { log.LogDebug($"Deleting job {jobId}"); } IJobEntity job = commandContext.JobEntityManager.FindById <IJobEntity>(new KeyValuePair <string, object>("id", jobId)); if (job == null) { throw new ActivitiObjectNotFoundException("No job found with id '" + jobId + "'", typeof(IJob)); } // We need to check if the job was locked, ie acquired by the job acquisition thread // This happens if the the job was already acquired, but not yet executed. // In that case, we can't allow to delete the job. if (job.LockOwner is object) { throw new ActivitiException("Cannot delete job when the job is being executed. Try again later."); } return(job); }
public void 创建自启动任务([FromServices] IProcessEngine processEngine) { ProcessEngineConfigurationImpl configuration = processEngine.ProcessEngineConfiguration as ProcessEngineConfigurationImpl; // 时间计算 DateTime now = DateTime.Now; // delay为相较当前时间,延时的时间变量 DateTime target = now.AddMinutes(1); // 时间事件声明 //ITimerJobEntity timer = new TimerJobEntityImpl() //{ // Id = configuration.IdGenerator.NextId, // Duedate = target, // Exclusive = true, // JobHandlerConfiguration = "Process_eJKiMV6cs",// 这里存入需要启动的流程key // JobHandlerType = TimerStartEventJobHandler.TYPE //}; //configuration.CommandContextFactory.createCommandContext() //ITimerJobEntity timer = configuration.TimerJobDataManager.create(); //timer.Id = configuration.IdGenerator.NextId; //timer.Duedate = target; //timer.Exclusive = true; //timer.JobHandlerConfiguration = "Process_eJKiMV6cs";// 这里存入需要启动的流程key //timer.JobHandlerType = TimerStartEventJobHandler.TYPE; //configuration.JobManager.scheduleTimerJob(timer); IJobEntity timer = configuration.CommandExecutor.Execute <IJobEntity>(new CreateTimerStartJobCmd("Process_b55g1NTCp", DateTime.Now.AddMinutes(1), "Task_1gfchcb")); //processEngine.RepositoryService. // 保存作业事件 //Context.CommandContext.JobEntityManager.insert(timer); }
/// <summary> /// /// </summary> /// <param name="jobEntity"></param> protected internal virtual void TriggerExecutorIfNeeded(IJobEntity jobEntity) { // When the async executor is activated, the job is directly passed on to the async executor thread if (AsyncExecutorActive) { HintAsyncExecutor(jobEntity); } }
/// <summary> /// /// </summary> /// <param name="jobEntity"></param> protected internal virtual void ExecuteMessageJob(IJobEntity jobEntity) { ExecuteJobHandler(jobEntity); if (!(jobEntity.Id is null)) { Context.CommandContext.JobEntityManager.Delete(jobEntity); } }
protected internal virtual void LockJob(ICommandContext commandContext, IJobEntity job, int lockTimeInMillis) { var cl = new DateTime(commandContext.ProcessEngineConfiguration.Clock.CurrentTime.Ticks); cl.AddMilliseconds(lockTimeInMillis); job.LockOwner = asyncExecutor.LockOwner; job.LockExpirationTime = cl; }
public virtual object Execute(ICommandContext commandContext) { IJobEntity jobToDelete = GetJobToDelete(commandContext); SendCancelEvent(jobToDelete); commandContext.JobEntityManager.Delete(jobToDelete); return(null); }
public override void Execute(IJobEntity job, string configuration, IExecutionEntity execution, ICommandContext commandContext) { JToken cfgJson = JToken.FromObject(configuration); string processDefinitionId = job.ProcessDefinitionId; bool activateProcessInstances = GetIncludeProcessInstances(cfgJson); ActivateProcessDefinitionCmd activateProcessDefinitionCmd = new ActivateProcessDefinitionCmd(processDefinitionId, null, activateProcessInstances, DateTime.Now, job.TenantId); activateProcessDefinitionCmd.Execute(commandContext); }
public override void Execute(IJobEntity job, string configuration, IExecutionEntity execution, ICommandContext commandContext) { JToken cfgJson = JToken.FromObject(configuration); string processDefinitionId = job.ProcessDefinitionId; bool suspendProcessInstances = GetIncludeProcessInstances(cfgJson); SuspendProcessDefinitionCmd suspendProcessDefinitionCmd = new SuspendProcessDefinitionCmd(processDefinitionId, null, suspendProcessInstances, null, job.TenantId); suspendProcessDefinitionCmd.Execute(commandContext); }
/// <summary> /// /// </summary> /// <param name="timerEntity"></param> /// <param name="variableScope"></param> protected internal virtual void RestoreExtraData(IJobEntity timerEntity, IVariableScope variableScope) { string activityId = timerEntity.JobHandlerConfiguration; if (timerEntity.JobHandlerType.Equals(TimerStartEventJobHandler.TYPE, StringComparison.CurrentCultureIgnoreCase) || timerEntity.JobHandlerType.Equals(TriggerTimerEventJobHandler.TYPE, StringComparison.CurrentCultureIgnoreCase)) { activityId = TimerEventHandler.GetActivityIdFromConfiguration(timerEntity.JobHandlerConfiguration); string endDateExpressionString = TimerEventHandler.GetEndDateFromConfiguration(timerEntity.JobHandlerConfiguration); if (!(endDateExpressionString is null)) { IExpression endDateExpression = processEngineConfiguration.ExpressionManager.CreateExpression(endDateExpressionString); string endDateString = null; IBusinessCalendar businessCalendar = processEngineConfiguration.BusinessCalendarManager.GetBusinessCalendar(GetBusinessCalendarName(TimerEventHandler.GeCalendarNameFromConfiguration(timerEntity.JobHandlerConfiguration), variableScope)); if (endDateExpression != null) { object endDateValue = endDateExpression.GetValue(variableScope); if (endDateValue is string) { endDateString = (string)endDateValue; } else if (endDateValue is DateTime) { timerEntity.EndDate = (DateTime)endDateValue; } else { throw new ActivitiException("Timer '" + ((IExecutionEntity)variableScope).ActivityId + "' was not configured with a valid duration/time, either hand in a java.util.Date or a String in format 'yyyy-MM-dd'T'hh:mm:ss'"); } if (!timerEntity.EndDate.HasValue) { timerEntity.EndDate = businessCalendar.ResolveEndDate(endDateString).GetValueOrDefault(); } } } } int maxIterations = 1; if (!(timerEntity.ProcessDefinitionId is null)) { Process process = ProcessDefinitionUtil.GetProcess(timerEntity.ProcessDefinitionId); maxIterations = GetMaxIterations(process, activityId); if (maxIterations <= 1) { maxIterations = GetMaxIterations(process, activityId); } } timerEntity.MaxIterations = maxIterations; }
public virtual void Execute(IJobEntity job, string configuration, IExecutionEntity execution, ICommandContext commandContext) { IEventSubscriptionEntityManager eventSubscriptionEntityManager = commandContext.EventSubscriptionEntityManager; // lookup subscription: IEventSubscriptionEntity eventSubscriptionEntity = eventSubscriptionEntityManager.FindById <IEventSubscriptionEntity>(new KeyValuePair <string, object>("id", configuration)); // if event subscription is null, ignore if (eventSubscriptionEntity != null) { eventSubscriptionEntityManager.EventReceived(eventSubscriptionEntity, null, false); } }
/// <summary> /// /// </summary> /// <param name="jobEntity"></param> protected internal virtual void ExecuteJobHandler(IJobEntity jobEntity) { IExecutionEntity execution = null; if (!(jobEntity.ExecutionId is null)) { execution = ExecutionEntityManager.FindById <ExecutionEntityImpl>(jobEntity.ExecutionId); } IDictionary <string, IJobHandler> jobHandlers = processEngineConfiguration.JobHandlers; IJobHandler jobHandler = jobHandlers[jobEntity.JobHandlerType]; jobHandler.Execute(jobEntity, jobEntity.JobHandlerConfiguration, execution, CommandContext); }
public virtual void Execute(IJobEntity job, string configuration, IExecutionEntity execution, ICommandContext commandContext) { Context.Agenda.PlanTriggerExecutionOperation(execution); if (commandContext.EventDispatcher.Enabled) { commandContext.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.TIMER_FIRED, job)); } if (execution.CurrentFlowElement is BoundaryEvent) { IList <string> processedElements = new List <string>(); DispatchExecutionTimeOut(job, execution, processedElements, commandContext); } }
protected internal virtual int CalculateRepeatValue(IJobEntity timerEntity) { int times = -1; IList <string> expression = new List <string>(timerEntity.Repeat.Split("/", true)); if (expression.Count > 1 && expression[0].StartsWith("R", StringComparison.Ordinal) && expression[0].Length > 1) { times = int.Parse(expression[0].Substring(1)); if (times > 0) { times--; } } return(times); }
protected internal virtual void SetNewRepeat(IJobEntity timerEntity, int newRepeatValue) { IList <string> expression = new List <string>(timerEntity.Repeat.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)); expression = expression.Skip(1).Take(expression.Count).ToList(); StringBuilder repeatBuilder = new StringBuilder("R"); repeatBuilder.Append(newRepeatValue); foreach (string value in expression) { repeatBuilder.Append("/"); repeatBuilder.Append(value); } timerEntity.Repeat = repeatBuilder.ToString(); }
public virtual void Execute(IJobEntity job, string configuration, IExecutionEntity execution, ICommandContext commandContext) { IProcessDefinitionEntity processDefinitionEntity = ProcessDefinitionUtil.GetProcessDefinitionFromDatabase(job.ProcessDefinitionId); // From DB -> need to get latest suspended state if (processDefinitionEntity == null) { throw new ActivitiException("Could not find process definition needed for timer start event"); } try { if (!processDefinitionEntity.Suspended) { if (commandContext.EventDispatcher.Enabled) { commandContext.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.TIMER_FIRED, job)); } // Find initial flow element matching the signal start event Process process = ProcessDefinitionUtil.GetProcess(job.ProcessDefinitionId); string activityId = GetActivityIdFromConfiguration(configuration); if (string.IsNullOrWhiteSpace(activityId) == false) { FlowElement flowElement = process.GetFlowElement(activityId, true); if (flowElement == null) { throw new ActivitiException("Could not find matching FlowElement for activityId " + activityId); } ProcessInstanceHelper processInstanceHelper = commandContext.ProcessEngineConfiguration.ProcessInstanceHelper; processInstanceHelper.CreateAndStartProcessInstanceWithInitialFlowElement(processDefinitionEntity, null, null, flowElement, process, null, null, true); } else { (new StartProcessInstanceCmd(processDefinitionEntity.Key, null, null, null, job.TenantId)).Execute(commandContext); } } else { log.LogDebug($"ignoring timer of suspended process definition {processDefinitionEntity.Name}"); } } catch (Exception e) { log.LogError($"exception during timer execution: {e.Message}"); throw new ActivitiException("exception during timer execution: " + e.Message, e); } }
protected internal virtual void ScheduleEventAsync(IEventSubscriptionEntity eventSubscriptionEntity, object payload) { IJobEntity message = JobEntityManager.Create(); message.JobType = JobFields.JOB_TYPE_MESSAGE; message.JobHandlerType = ProcessEventJobHandler.TYPE; message.JobHandlerConfiguration = eventSubscriptionEntity.Id; message.TenantId = eventSubscriptionEntity.TenantId; // TODO: support payload // if(payload != null) { // message.setEventPayload(payload); // } JobManager.ScheduleAsyncJob(message); }
/// <summary> /// /// </summary> /// <param name="jobEntity"></param> /// <param name="execution"></param> /// <param name="exclusive"></param> protected internal virtual void FillDefaultAsyncJobInfo(IJobEntity jobEntity, IExecutionEntity execution, bool exclusive) { jobEntity.JobType = JobFields.JOB_TYPE_MESSAGE; jobEntity.Revision = 1; jobEntity.Retries = processEngineConfiguration.AsyncExecutorNumberOfRetries; jobEntity.ExecutionId = execution.Id; jobEntity.ProcessInstanceId = execution.ProcessInstanceId; jobEntity.ProcessDefinitionId = execution.ProcessDefinitionId; jobEntity.Exclusive = exclusive; jobEntity.JobHandlerType = AsyncContinuationJobHandler.TYPE; // Inherit tenant id (if applicable) if (!(execution.TenantId is null)) { jobEntity.TenantId = execution.TenantId; } }
/// <summary> /// /// </summary> /// <param name="execution"></param> /// <param name="exclusive"></param> /// <returns></returns> protected internal virtual IJobEntity InternalCreateLockedAsyncJob(IExecutionEntity execution, bool exclusive) { IJobEntity asyncJob = processEngineConfiguration.JobEntityManager.Create(); FillDefaultAsyncJobInfo(asyncJob, execution, exclusive); //GregorianCalendar gregorianCalendar = new GregorianCalendar(); //gregorianCalendar.Time = processEngineConfiguration.Clock.CurrentTime; //gregorianCalendar.add(DateTime.MILLISECOND, AsyncExecutor.AsyncJobLockTimeInMillis); //asyncJob.LockExpirationTime = gregorianCalendar.Time; //将job锁定为一定时间(默认30秒) asyncJob.LockExpirationTime = DateTime.Now.AddMilliseconds(AsyncExecutor.AsyncJobLockTimeInMillis); asyncJob.LockOwner = AsyncExecutor.LockOwner; return(asyncJob); }
/// <summary> /// /// </summary> /// <param name="timerEntity"></param> protected internal virtual void ExecuteTimerJob(IJobEntity timerEntity) { ITimerJobEntityManager timerJobEntityManager = processEngineConfiguration.TimerJobEntityManager; IVariableScope variableScope = null; if (!(timerEntity.ExecutionId is null)) { variableScope = ExecutionEntityManager.FindById <VariableScopeImpl>(timerEntity.ExecutionId); } if (variableScope == null) { variableScope = NoExecutionVariableScope.SharedInstance; } // set endDate if it was set to the definition RestoreExtraData(timerEntity, variableScope); if (timerEntity.Duedate != null && !IsValidTime(timerEntity, timerEntity.Duedate.GetValueOrDefault(DateTime.Now), variableScope)) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug($"Timer {timerEntity.Id} fired. but the dueDate is after the endDate. Deleting timer."); } processEngineConfiguration.JobEntityManager.Delete(timerEntity); return; } ExecuteJobHandler(timerEntity); processEngineConfiguration.JobEntityManager.Delete(timerEntity); if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug($"Timer {timerEntity.Id} fired. Deleting timer."); } if (!(timerEntity.Repeat is null)) { ITimerJobEntity newTimerJobEntity = timerJobEntityManager.CreateAndCalculateNextTimer(timerEntity, variableScope); if (newTimerJobEntity != null) { ScheduleTimerJob(newTimerJobEntity); } } }
/// <summary> /// /// </summary> /// <param name="timerJob"></param> /// <returns></returns> public virtual IJobEntity MoveTimerJobToExecutableJob(ITimerJobEntity timerJob) { if (timerJob == null) { throw new ActivitiException("Empty timer job can not be scheduled"); } IJobEntity executableJob = CreateExecutableJobFromOtherJob(timerJob); bool insertSuccesful = processEngineConfiguration.JobEntityManager.InsertJobEntity(executableJob); if (insertSuccesful) { processEngineConfiguration.TimerJobEntityManager.Delete(timerJob); TriggerExecutorIfNeeded(executableJob); return(executableJob); } return(null); }
protected internal virtual ITimerJobEntity CreateTimer(IJobEntity te) { ITimerJobEntity newTimerEntity = Create(); newTimerEntity.JobHandlerConfiguration = te.JobHandlerConfiguration; newTimerEntity.JobHandlerType = te.JobHandlerType; newTimerEntity.Exclusive = te.Exclusive; newTimerEntity.Repeat = te.Repeat; newTimerEntity.Retries = te.Retries; newTimerEntity.EndDate = te.EndDate; newTimerEntity.ExecutionId = te.ExecutionId; newTimerEntity.ProcessInstanceId = te.ProcessInstanceId; newTimerEntity.ProcessDefinitionId = te.ProcessDefinitionId; // Inherit tenant newTimerEntity.TenantId = te.TenantId; newTimerEntity.JobType = JobFields.JOB_TYPE_TIMER; return(newTimerEntity); }
/// <summary> /// /// </summary> /// <param name="job"></param> /// <returns></returns> protected internal virtual IJobEntity CreateExecutableJobFromOtherJob(IAbstractJobEntity job) { IJobEntity executableJob = processEngineConfiguration.JobEntityManager.Create(); CopyJobInfo(executableJob, job); if (AsyncExecutorActive) { //GregorianCalendar gregorianCalendar = new GregorianCalendar(); //gregorianCalendar.Time = processEngineConfiguration.Clock.CurrentTime; //gregorianCalendar.add(DateTime.MILLISECOND, AsyncExecutor.TimerLockTimeInMillis); //将job锁定为一定时间(默认30秒) executableJob.LockExpirationTime = DateTime.Now.AddMilliseconds(AsyncExecutor.TimerLockTimeInMillis); executableJob.LockOwner = AsyncExecutor.LockOwner; } return(executableJob); }
public virtual object Execute(ICommandContext commandContext) { IJobEntity job = commandContext.JobEntityManager.FindById <IJobEntity>(jobId); if (job != null) { job.Retries = retries; if (commandContext.EventDispatcher.Enabled) { commandContext.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.ENTITY_UPDATED, job)); } } else { throw new ActivitiObjectNotFoundException("No job found with id '" + jobId + "'.", typeof(IJob)); } return(null); }
/// <summary> /// /// </summary> /// <param name="deadLetterJobEntity"></param> /// <param name="retries"></param> /// <returns></returns> public virtual IJobEntity MoveDeadLetterJobToExecutableJob(IDeadLetterJobEntity deadLetterJobEntity, int retries) { if (deadLetterJobEntity == null) { throw new ActivitiIllegalArgumentException("Null job provided"); } IJobEntity executableJob = CreateExecutableJobFromOtherJob(deadLetterJobEntity); executableJob.Retries = retries; bool insertSuccesful = processEngineConfiguration.JobEntityManager.InsertJobEntity(executableJob); if (insertSuccesful) { processEngineConfiguration.DeadLetterJobEntityManager.Delete(deadLetterJobEntity); TriggerExecutorIfNeeded(executableJob); return(executableJob); } return(null); }
public virtual ITimerJobEntity CreateAndCalculateNextTimer(IJobEntity timerEntity, IVariableScope variableScope) { int repeatValue = CalculateRepeatValue(timerEntity); if (repeatValue != 0) { if (repeatValue > 0) { SetNewRepeat(timerEntity, repeatValue); } DateTime?newTimer = CalculateNextTimer(timerEntity, variableScope); if (newTimer != null && IsValidTime(timerEntity, newTimer, variableScope)) { ITimerJobEntity te = CreateTimer(timerEntity); te.Duedate = newTimer; return(te); } } return(null); }
/// <summary> /// /// </summary> /// <param name="job"></param> /// <returns></returns> public virtual IAbstractJobEntity ActivateSuspendedJob(ISuspendedJobEntity job) { IAbstractJobEntity activatedJob; if (JobFields.JOB_TYPE_TIMER.Equals(job.JobType)) { activatedJob = CreateTimerJobFromOtherJob(job); processEngineConfiguration.TimerJobEntityManager.Insert((ITimerJobEntity)activatedJob); } else { activatedJob = CreateExecutableJobFromOtherJob(job); IJobEntity jobEntity = (IJobEntity)activatedJob; processEngineConfiguration.JobEntityManager.Insert(jobEntity); TriggerExecutorIfNeeded(jobEntity); } processEngineConfiguration.SuspendedJobEntityManager.Delete(job); return(activatedJob); }