public virtual JobEntity createSeedJob() { JobEntity seedJob = BATCH_SEED_JOB_DECLARATION.createJobInstance(this); Context.CommandContext.JobManager.insertAndHintJobExecutor(seedJob); return(seedJob); }
protected internal virtual ScopeImpl DetermineTimerTriggerTargetScope(JobEntity jobEntity, ScopeImpl targetScope) { if (TimerStartEventSubprocessJobHandler.TYPE.Equals(jobEntity.JobHandlerType)) { return(targetScope.FlowScope); } return(targetScope); }
/// <inheritdoc /> /// <summary> /// Removes the specified job from the repository. /// </summary> /// <param name="id">The id of the job to remove.</param> /// <returns><see cref="Task" />.</returns> public async Task Remove(string id) { JobEntity entity = await _context.Jobs.FirstAsync(t => t.Id.Equals(id)); _context.Jobs.Remove(entity); await _context.SaveChangesAsync(); }
public async Task <int> UpdateExecuteAsync(string Group, string Name, DateTime?PreviousFireTime, DateTime?NextFireTime) { JobEntity model = await _jobRepository.GetAsync(new { Group, Name }); model.LastOpTime = PreviousFireTime; model.NextOpTime = NextFireTime; return(await _jobRepository.UpdateAsync(model)); }
protected internal virtual void LogException(JobEntity job) { if (Exception != null) { job.ExceptionMessage = Exception.Message; job.ExceptionStacktrace = ExceptionStacktrace; } }
public MigratingTimerJobInstance(JobEntity jobEntity, JobDefinitionEntity jobDefinitionEntity, ScopeImpl targetScope, bool updateEvent, TimerDeclarationImpl targetTimerDeclaration) : base(jobEntity, jobDefinitionEntity, targetScope) { TimerTriggerTargetScope = DetermineTimerTriggerTargetScope(jobEntity, targetScope); this.UpdateEvent = updateEvent; TargetJobDeclaration = targetTimerDeclaration; }
protected internal virtual JobEntity createNonExclusiveJob(string id, string processInstanceId) { JobEntity job = mock(typeof(JobEntity)); when(job.Id).thenReturn(id); when(job.ProcessInstanceId).thenReturn(processInstanceId); return(job); }
public virtual JobEntity CreateSeedJob() { JobEntity seedJob = BatchSeedJobDeclaration.CreateJobInstance(this); Context.CommandContext.JobManager.InsertAndHintJobExecutor(seedJob); return(seedJob); }
/// <summary> /// Adds the specified job to the repository. /// </summary> /// <param name="job">The job.</param> /// <returns> /// <see cref="JobEntity" />. /// </returns> public async Task <JobEntity> Add(JobEntity job) { await _context.Jobs.AddAsync(job); await _context.SaveChangesAsync(); return(job); }
public bool Insert(JobEntity jobEntity) { using (var db = _dbContext.GetIntance()) { var count = db.Insertable(jobEntity).ExecuteCommand(); result = count > 0 ? true : false; } return(result); }
protected internal virtual void InitHistoricJobLogEvent(HistoricJobLogEventEntity evt, IJob job, HistoryEventTypes eventType) { evt.TimeStamp = ClockUtil.CurrentTime; JobEntity jobEntity = (JobEntity)job; evt.JobId = jobEntity.Id; evt.JobDueDate = jobEntity.Duedate; evt.JobRetries = jobEntity.Retries; evt.JobPriority = jobEntity.Priority; IJobDefinition jobDefinition = jobEntity.JobDefinition; if (jobDefinition != null) { evt.JobDefinitionId = jobDefinition.Id; evt.JobDefinitionType = jobDefinition.JobType; evt.JobDefinitionConfiguration = jobDefinition.JobConfiguration; } else { // in case of async signal there does not exist a job definition // but we use the jobHandlerType as jobDefinitionType evt.JobDefinitionType = jobEntity.JobHandlerType; } evt.ActivityId = jobEntity.ActivityId; evt.ExecutionId = jobEntity.ExecutionId; evt.ProcessInstanceId = jobEntity.ProcessInstanceId; evt.ProcessDefinitionId = jobEntity.ProcessDefinitionId; evt.ProcessDefinitionKey = jobEntity.ProcessDefinitionKey; evt.DeploymentId = jobEntity.DeploymentId; evt.TenantId = jobEntity.TenantId; // initialize sequence counter InitSequenceCounter(jobEntity, evt); IJobState state = null; if (HistoryEventTypes.JobCreate.Equals(eventType)) { state = JobStateFields.Created; } else if (HistoryEventTypes.JobFail.Equals(eventType)) { state = JobStateFields.Failed; } else if (HistoryEventTypes.JobSuccess.Equals(eventType)) { state = JobStateFields.Successful; } else if (HistoryEventTypes.JobDelete.Equals(eventType)) { state = JobStateFields.Deleted; } evt.State = state.StateCode; }
protected internal virtual void CreateOpLogEntry(CommandContext commandContext, long previousPriority, JobEntity job) { PropertyChange propertyChange = new PropertyChange(JobPriorityProperty, previousPriority, job.Priority); commandContext.OperationLogManager.LogJobOperation( UserOperationLogEntryFields.OperationTypeSetPriority, job.Id, job.JobDefinitionId, job.ProcessInstanceId, job.ProcessDefinitionId, job.ProcessDefinitionKey, propertyChange); }
/// <summary> /// Creates a connection to the jobs table and /// upserts the given job entity. /// </summary> /// <param name="log"></param> /// <param name="jobEntity"></param> /// <returns></returns> public static async Task UpdateJobTableWithStatus(ILogger log, JobEntity jobEntity) { log.LogInformation("[PENDING] Connecting to jobs table..."); JobTable jobTable = new JobTable(log, ConfigSettings.IMAGEJOBS_PARTITIONKEY); log.LogInformation("[SUCCESS] Connected to Jobs Table"); await jobTable.InsertOrReplaceJobEntity(jobEntity); }
protected internal virtual bool isFirstJobExecution(JobEntity job) { // check if this is jobs' first execution (recognize // this because no exception is set. Only the first // execution can be without exception - because if // no exception occurred the job would have been completed) // see https://app.camunda.com/jira/browse/CAM-1039 return(string.ReferenceEquals(job.ExceptionByteArrayId, null) && string.ReferenceEquals(job.ExceptionMessage, null)); }
protected internal virtual void checkJobType(JobEntity job) { string type = job.JobHandlerType; if (!(TimerExecuteNestedActivityJobHandler.TYPE.Equals(type) || TimerCatchIntermediateEventJobHandler.TYPE.Equals(type) || TimerStartEventJobHandler.TYPE.Equals(type) || TimerStartEventSubprocessJobHandler.TYPE.Equals(type)) || !(job is TimerEntity)) { throw new ProcessEngineException("Only timer jobs can be recalculated, but the job with id '" + jobId + "' is of type '" + type + "'."); } }
private async Task Start(JobEntity jobView) { var jobRuntime = await JobFactory.CreateJobRuntime(_serviceRoute, jobView); JobDataMap map = new JobDataMap { new KeyValuePair <string, object> ("JobRuntime", jobRuntime) }; IJobDetail job = JobBuilder.Create().OfType(typeof(JobImplementation)).WithIdentity(jobView.Id).UsingJobData(map).Build(); _scheduler.ListenerManager.AddJobListener(new JobListener(jobView.Id, JobWasExecuteCallBack), KeyMatcher <JobKey> .KeyEquals(new JobKey(jobView.Id))); if (!jobView.IsSimple) { if (!ValidExpression(jobView.CronExpression)) { throw new Exception("cron表达式验证失败"); } var trigger = new CronTriggerImpl { CronExpressionString = jobView.CronExpression, Name = jobView.Name, Key = new TriggerKey(jobView.Id), Description = jobView.Remark }; if (jobView.StartTime.HasValue) { trigger.StartTimeUtc = Utils.ConvertToDateTimeOffset(jobView.StartTime.Value); } if (jobView.EndTime.HasValue) { trigger.EndTimeUtc = Utils.ConvertToDateTimeOffset(jobView.EndTime.Value); } await _scheduler.ScheduleJob(job, trigger); } else { var triggerBuilder = TriggerBuilder.Create().WithIdentity(jobView.Id).WithSimpleSchedule(x => x.WithRepeatCount(jobView.RepeatCount).WithInterval(TimeSpan.FromSeconds(jobView.IntervalSeconds))); if (jobView.StartTime.HasValue) { var start = Utils.ConvertToDateTimeOffset(jobView.StartTime.Value); triggerBuilder = triggerBuilder.StartAt(start); } if (jobView.EndTime.HasValue) { var end = Utils.ConvertToDateTimeOffset(jobView.EndTime.Value); triggerBuilder = triggerBuilder.EndAt(end); } var trigger = triggerBuilder.Build(); await _scheduler.ScheduleJob(job, trigger); } _logger.Info($"job [{jobView.Id}]{jobView.Name} start success"); }
protected internal virtual void suspendJobs(IList <Job> jobs) { foreach (Job job in jobs) { JobEntity jobInstance = (JobEntity)job; jobInstance.SuspensionState = org.camunda.bpm.engine.impl.persistence.entity.SuspensionState_Fields.SUSPENDED.StateCode; jobInstance.Duedate = null; } }
public async Task CreateAsync(JobEntity job) { using (var connection = new SqlConnection(DBConnectionString)) { await connection.OpenAsync(); job.Id = await connection.QueryFirstOrDefaultAsync <int>("InsertJob", new { startTime = job.StartTime, endTime = job.EndTime, dateCreated = job.DateCreated }, commandType : CommandType.StoredProcedure); } }
public override void onDelete(BatchJobConfiguration configuration, JobEntity jobEntity) { string byteArrayId = configuration.ConfigurationByteArrayId; if (!string.ReferenceEquals(byteArrayId, null)) { Context.CommandContext.ByteArrayManager.deleteByteArrayById(byteArrayId); } }
protected internal virtual void switchVersionOfJob(JobEntity jobEntity, ProcessDefinitionEntity newProcessDefinition, IDictionary <string, string> jobDefinitionMapping) { jobEntity.ProcessDefinitionId = newProcessDefinition.Id; jobEntity.DeploymentId = newProcessDefinition.DeploymentId; string newJobDefinitionId = jobDefinitionMapping[jobEntity.JobDefinitionId]; jobEntity.JobDefinitionId = newJobDefinitionId; }
private bool EnqueueScheduledTaskAndRecalculateNextTime(ScheduleEntity scheduleEntity, string reasonToEnqueue, Func <ScheduledTask, ScheduledTask> caluculateNext, DbConnection connection) { var scheduledTask = ScheduleEntity.ToScheduleTask(scheduleEntity); //if calculate delegate exists, calculate next invocation and save, otherwise (manual trigger), skip if (caluculateNext != null) { scheduledTask = caluculateNext(scheduledTask); scheduleEntity.LastInvocation = scheduledTask.LastInvocation; scheduleEntity.NextInvocation = scheduledTask.NextInvocation; this._queryService.UpdateScheduledItem(scheduleEntity, t => new { t.LastInvocation, t.NextInvocation }, connection); } //if job scheduled if (!string.IsNullOrEmpty(scheduleEntity.JobInvocationData)) { var insertedJob = JobEntity.FromScheduleEntity(scheduledTask); insertedJob.ScheduleName = scheduleEntity.Name; var jobId = this._queryService.InsertJob(insertedJob, connection); var stateId = this._queryService.InsertJobState( StateEntity.FromIState(new EnqueuedState() { EnqueuedAt = DateTime.UtcNow, Queue = scheduledTask.Job.QueueName, Reason = reasonToEnqueue }, insertedJob.Id), connection); this._queryService.SetJobState(jobId, stateId, EnqueuedState.DefaultName, connection); this._queryService.InsertJobToQueue(jobId, scheduledTask.Job.QueueName, connection); return(true); } //if workflow scheduled else if (!string.IsNullOrEmpty(scheduleEntity.WorkflowInvocationData)) { var rootJobs = scheduledTask.Workflow.GetRootJobs().ToDictionary(t => t.TempId, null); scheduledTask.Workflow.SaveWorkflow((workflowJob) => { workflowJob.QueueJob.ScheduleName = scheduleEntity.Name; return(CreateAndEnqueueJob( queueJob: workflowJob.QueueJob, state: rootJobs.ContainsKey(workflowJob.TempId) ? new EnqueuedState() { EnqueuedAt = DateTime.UtcNow, Queue = workflowJob.QueueJob.QueueName, Reason = reasonToEnqueue } as IState : new AwaitingState() { Reason = "Waiting for other job/s to finish.", CreatedAt = DateTime.UtcNow } as IState, connection: connection )); }); return(true); } else { return(false); } }
public void OnDelete(IJobHandlerConfiguration configuration, JobEntity jobEntity) { var byteArrayId = ((BatchJobConfiguration)configuration).ConfigurationByteArrayId; if (!ReferenceEquals(byteArrayId, null)) { //Context.CommandContext.ByteArrayManager.deleteByteArrayById(byteArrayId); } }
public async Task <Result> TryCreate(Android android) { if (!android.IsValid) { return(new Result(false, "Android wasn`t created")); } if (await IsAndroid(android.Name)) { return(new Result(false, "Android with this name already exists")); } if (android.Skills.Where(s => !s.IsValid).Count() > 0) { return(new Result(false, "Android wasn`t created: skill error")); } AndroidEntity androidEntity = new AndroidEntity { Name = android.Name, Reliability = 10, Status = true, Avatar = android.Avatar }; JobEntity job = await _context.Jobs.FirstOrDefaultAsync(j => j.Id == android.JobId); if (job == null) { return(new Result(false, "Android wasn`t created: job error")); } androidEntity.Job = job; SkillEntity skillEntity; List <SkillToAndroidEntity> StoAs = new List <SkillToAndroidEntity>(); foreach (Skill s in android.Skills) { skillEntity = await _context.Skills.FirstOrDefaultAsync(e => e.Name == s.Name); StoAs.Add(new SkillToAndroidEntity { Skill = skillEntity, Android = androidEntity }); } await _context.Androids.AddAsync(androidEntity); await _context.SaveChangesAsync(); await _context.Entry(androidEntity).Collection(a => a.SkillsToAndroids).LoadAsync(); foreach (SkillToAndroidEntity s in StoAs) { androidEntity.SkillsToAndroids.Add(s); } _context.Update(androidEntity); await _context.SaveChangesAsync(); return(new Result(true)); }
public ActionResult GetJobList() { JobEntity para = new JobEntity(); para.LanguageKey = CurrentLanguge.LanguageKey; var list = JobBLL.Instance.GetList(para); return(Content(list.ToJson())); }
public virtual void deleteJob(JobEntity job, bool fireDeleteEvent) { DbEntityManager.delete(job); if (fireDeleteEvent) { HistoricJobLogManager.fireJobDeletedEvent(job); } }
public Task <bool> StartJob(JobEntity job, ServiceRouteDescriptor service) { var client = _clientFactory.Get(service); var jobRequest = Utils.MapperGrpcJob <JobEntity, Job>(job); var response = client.StartJob(jobRequest); return(Task.FromResult(response.Success)); }
public void Execute(IJobHandlerConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, string tenantId) { var conf = (HistoryCleanupJobHandlerConfiguration)configuration; //find JobEntity JobEntity jobEntity = commandContext.JobManager.FindJobByHandlerType(Type); bool rescheduled = false; if (conf.ImmediatelyDue || (HistoryCleanupHelper.IsBatchWindowConfigured(commandContext) && HistoryCleanupHelper.IsWithinBatchWindow(ClockUtil.CurrentTime, commandContext))) { //find data to delete HistoryCleanupBatch nextBatch = HistoryCleanupHelper.GetNextBatch(commandContext); if (nextBatch.Size() >= GetBatchSizeThreshold(commandContext)) { //delete bunch of data nextBatch.PerformCleanup(); //ReSchedule now commandContext.JobManager.ReSchedule(jobEntity, ClockUtil.CurrentTime); rescheduled = true; CancelCountEmptyRuns(conf, jobEntity); } else { //still have something to delete if (nextBatch.Size() > 0) { nextBatch.PerformCleanup(); } //not enough data for cleanup was found if (HistoryCleanupHelper.IsWithinBatchWindow(ClockUtil.CurrentTime, commandContext)) { //ReSchedule after some delay DateTime nextRunDate = conf.GetNextRunWithDelay(ClockUtil.CurrentTime); if (HistoryCleanupHelper.IsWithinBatchWindow(nextRunDate, commandContext)) { commandContext.JobManager.ReSchedule(jobEntity, nextRunDate); rescheduled = true; IncrementCountEmptyRuns(conf, jobEntity); } } } } if (!rescheduled) { if (HistoryCleanupHelper.IsBatchWindowConfigured(commandContext)) { ReScheduleRegularCall(commandContext, jobEntity); } else { //nothing more to do, suspend the job SuspendJob(jobEntity); } CancelCountEmptyRuns(conf, jobEntity); } }
public static async Task LoadServerEntity() { RoleplayContext ctx = Singleton.GetDatabaseInstance(); using (UnitOfWork unit = new UnitOfWork(ctx)) { await BuildingEntity.LoadBuildingsAsync(unit); await AtmEntity.LoadAtmsAsync(unit); await BusEntity.LoadBusAsync(unit); await ShopEntity.LoadShopAsync(unit); await GroupEntity.LoadGroupsAsync(unit); await WarehouseOrderEntity.LoadWarehouseOrdersAsync(); } JobEntity courierJob = new JobEntity(new JobEntityModel() { JobName = "Kurier", VehicleModel = AltV.Net.Enums.VehicleModel.Boxville2, RespawnVehicle = true, Position = new Position(26.1626f, -1300.59f, 29.2124f), RespawnVehiclePosition = new Position(36.9495f, -1283.84f, 29.2799f), RespawnVehicleRotation = new Rotation(0, 0, 1.53369f), JobType = JobType.Courier, MaxSalary = 400 }); courierJob.Create(); JobEntity junkerJob = new JobEntity(new JobEntityModel() { JobName = "Śmieciarz", VehicleModel = AltV.Net.Enums.VehicleModel.Trash, RespawnVehicle = true, Position = new Position(500.334f, -652.009f, 24.8989f), RespawnVehiclePosition = new Position(508.286f, -609.771f, 25.1348f), RespawnVehicleRotation = new Rotation(0, 0, 1.63264f), JobType = JobType.Junker, MaxSalary = 400 }); junkerJob.Create(); JobCenterEntity jobCenter = new JobCenterEntity(new JobCenterModel() { Id = 0, Position = new Position(104.73f, -934.075f, 29.8022f), Jobs = EntityHelper.GetJobs() }); jobCenter.Spawn(); }
public IHttpActionResult PostJobEntity(JobEntityDTO jobEntityDTO) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var jobEntity = new JobEntity { EntityId = jobEntityDTO.EntityId, JobId = jobEntityDTO.JobId, MethodToNotify = jobEntityDTO.MethodToNotify, NotifyTime = jobEntityDTO.NotifyTime }; var jobInDb = db.Jobs.Find(jobEntity.JobId); if (jobInDb == null) { return(NotFound()); } jobEntity.Job = jobInDb; var entityInDb = db.Entities.Find(jobEntity.EntityId); if (entityInDb == null) { return(NotFound()); } jobEntity.Entity = entityInDb; //db.JobEntities.Add(); try { db.SaveChanges(); } catch (DbUpdateException) { if (JobEntityExists(jobEntityDTO.JobEntityId)) { return(Conflict()); } else { throw; } } return(CreatedAtRoute("DefaultApi", new { id = jobEntityDTO.JobEntityId }, jobEntityDTO)); }
public IQueryable <Job> GetBatchStatus(string batchId, int numOfRecords = 1000, string continuationToken = "") { try { // Parameter Validations GeresAssertionHelper.AssertNullOrEmpty(batchId, "batchId"); // Log the query request GeresEventSource.Log.WebApiMonitoringQueryBatchReceived(batchId); using (var repo = RepositoryFactory.CreateJobsRepository(CloudConfigurationManager.GetSetting(GlobalConstants.STORAGE_CONNECTIONSTRING_CONFIGNAME))) { var jobEntities = repo.GetJobs(batchId, numOfRecords, ref continuationToken); if (jobEntities == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } List <Job> jobs = new List <Job>(); foreach (JobEntity je in jobEntities) { Job job = JobEntity.ConvertToJob(je); jobs.Add(job); } // If the continuation token is not null, add it to the HTTP Header if (!string.IsNullOrEmpty(continuationToken)) { System.Web.HttpContext.Current.Response.AddHeader("gerespagingtoken", continuationToken); } // Log the query completion GeresEventSource.Log.WebApiMonitoringQueryBatchSuccessful(batchId, jobs.Count); return(jobs.AsQueryable()); } } catch (HttpResponseException ex) { throw ex; } catch (ArgumentException ex) { Trace.TraceWarning("WebAPI - JobMonitorController -- Invalid parameter passed into system: {0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace); GeresEventSource.Log.WebApiBatchMonitoringInvalidParameterReceived(batchId, ex.Message, ex.StackTrace); throw new HttpResponseException(HttpStatusCode.BadRequest); } catch (Exception ex) { Trace.TraceError("WebAPI - JobMonitorController -- Unknown exception occured: {0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace); GeresEventSource.Log.WebApiUnknownExceptionOccured(ex.Message, ex.StackTrace); throw new HttpResponseException(HttpStatusCode.InternalServerError); } }