Пример #1
0
		public void Work (int Amount)
		{
			if (state != JobState.Success) {
				state = JobState.Working;
				//targetThing.Work (Amount);
			}
		}
Пример #2
0
 public Job(string name, TimeSpan period)
 {
     _Name = name;
     _Period = period;
     _State = JobState.Waiting;
     _NextExecution = DateTime.Now.Add(TimeSpan.FromSeconds(5));
 }
 public JobModel(int id, string name, JobState state, RunModel run = null)
 {
     JobID = id;
     JobName = name;
     State = state;
     Run = run;
 }
 /// <summary>
 /// Returns publish related jobs in a specified state.
 /// </summary>
 /// <param name="state"></param>
 /// <returns></returns>
 public static IEnumerable<PublishJobEntry> GetJobs(JobState state)
 {
     var jobs = JobManager.GetJobs();
      var publishJobs =
     jobs.Where(job => job.Category.Equals("publish", StringComparison.InvariantCultureIgnoreCase) && job.Status.State == state).Select(
        job => new PublishJobEntry(job.Handle, job.Name, job.Category, job.Status, job.Options.ContextUser));
      List<PublishJobEntry> jobList = new List<PublishJobEntry>(publishJobs);
      return jobList;
 }
Пример #5
0
        public static JobProgressDto GetProgressDto(this JobState state)
        {
            //todo: smarter logic
            var dbstate = new DatabaseJobState(state);

            return(new JobProgressDto()
            {
                Total = dbstate.LastDiscoverBatchCount,
                Current = dbstate.BatchCount
            });
        }
Пример #6
0
 protected virtual void LogTask(JobState state, string taskName, Exception?exception = null)
 {
     if (exception == null)
     {
         Log.Write("Jobs", state == JobState.Finish ? "Task Success" : $"Task {state}", ("TaskName", taskName));
     }
     else
     {
         Log.Write(exception, ("TaskName", taskName));
     }
 }
Пример #7
0
 protected virtual void LogTask(JobState state, string taskName, Exception?exception = null)
 {
     if (exception == null)
     {
         this.Log.LogInformation(state == JobState.Finish ? "Task Success" : $"Task {state}", ("TaskName", taskName));
     }
     else
     {
         this.Log.LogError(exception, "Task failed - " + taskName);
     }
 }
Пример #8
0
 private void Apply(JobAdded @event)
 {
     _state = new JobState
     {
         Id         = new NonEmptyIdentity(Id),
         Name       = new JobName(@event.Name),
         Status     = @event.Status,
         UserId     = new NonEmptyIdentity(@event.UserId),
         WorkshopId = new NonEmptyIdentity(@event.WorkshopId),
     };
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="methodName"></param>
 /// <param name="from"></param>
 /// <param name="count"></param>
 public DisableConcurrentlyJobExecutionAttribute(string methodName, int from = 0, int count = 2000, JobState jobState = JobState.DeletedState)
 {
     if (string.IsNullOrEmpty(methodName))
     {
         throw new ArgumentNullException(nameof(methodName));
     }
     _jobState   = jobState;
     _from       = from;
     _count      = count;
     _methodName = methodName;
 }
Пример #10
0
 protected virtual void LogTask(JobState state, string taskName, Exception exception = null)
 {
     if (exception == null)
     {
         Log.Write("Jobs", "Task Success", ("TaskName", taskName));
     }
     else
     {
         Log.Write(exception, ("TaskName", taskName));
     }
 }
        IsJobComplete(
            object jobStateObj)
        {
            JobState jobState = (JobState)((ushort)jobStateObj);

            //Console.WriteLine(jobState);

            return((jobState == JobState.Completed) ||
                   (jobState == JobState.CompletedWithWarnings) || (jobState == JobState.Terminated) ||
                   (jobState == JobState.Exception) || (jobState == JobState.Killed));
        }
Пример #12
0
        public SpeechRecognitionClient(bool usebingspeechservice = false)
        {
            lineSeparator = "\r\n"; // Environment.NewLine;

            state = JobState.Initializing;
            // Set usebingspeechservice to true in  the client constructor if you want to use the old Bing Speech SDK
            // instead of the new Speech Service.
            useClassicBingSpeechService = usebingspeechservice;

            state = JobState.Ready;
        }
Пример #13
0
 internal bool IsFinishedState(JobState state)
 {
     if (state == JobState.Completed || state == JobState.Failed)
     {
         return(true);
     }
     else
     {
         return(state == JobState.Stopped);
     }
 }
Пример #14
0
        internal static bool IsJobComplete(object jobStateObj)
        {
            JobState jobState = (JobState)(ushort)jobStateObj;

            return
                ((jobState == JobState.Completed) ||
                 (jobState == JobState.CompletedWithWarnings) ||
                 (jobState == JobState.Terminated) ||
                 (jobState == JobState.Exception) ||
                 (jobState == JobState.Killed));
        }
Пример #15
0
 internal JobStateAutoGenerated(string displayName, DateTimeOffset createdDateTime, DateTimeOffset?expirationDateTime, Guid jobId, DateTimeOffset lastUpdateDateTime, JobState status, IReadOnlyList <GeneratedError> errors, string nextLink)
 {
     DisplayName        = displayName;
     CreatedDateTime    = createdDateTime;
     ExpirationDateTime = expirationDateTime;
     JobId = jobId;
     LastUpdateDateTime = lastUpdateDateTime;
     Status             = status;
     Errors             = errors;
     NextLink           = nextLink;
 }
Пример #16
0
        protected void OnFinished()
        {
            Log.Debug("Finished", Title);
            pause_event = null;

            if (state != JobState.Cancelled)
            {
                State = JobState.Completed;
            }

            Finished?.Invoke(this, EventArgs.Empty);
        }
Пример #17
0
 protected virtual void LogJob(JobState state,
                               JobInfo job,
                               string runId,
                               Exception exception = null)
 => this.Repository.Log(new JobLog
 {
     JobName   = job.Name,
     RunId     = runId,
     CreatedOn = DateTime.UtcNow,
     Status    = state,
     Error     = exception?.ToString() ?? String.Empty
 });
        public async Task <ActionResult <JobStateVM> > GetJobState([FromRoute] Guid id)
        {
            JobState jobstate = await this.bll.GetJobStateByIdAsync(id);

            if (jobstate == null)
            {
                return(NotFound());
            }

            // Mapping
            return(Ok(this.mapper.Map <JobState, JobStateVM>(jobstate)));
        }
Пример #19
0
 public JobItem(string sourceFile, string destFile, string profileName)
 {
     this._sourceFile  = sourceFile;
     this._destFile    = destFile;
     this._profileName = profileName;
     this._videoInfo   = new VideoInfo(sourceFile);
     this._audioInfo   = new AudioInfo(sourceFile);
     string[] items = new string[] { "未处理", sourceFile, destFile };
     this._cxListViewItem         = new Cxgui.Job.CxListViewItem(items);
     this._cxListViewItem.JobItem = this;
     this._state = JobState.NotProccessed;
 }
Пример #20
0
        public bool CheckIsRunning()
        {
            var result = Process != null && Process.Running;

            if (State == JobState.Running && result == false)
            {
                Logger.Warning($"Service terminated unexpectedly: '{Command}'");
                State = JobState.Inactive;
            }

            return(result);
        }
Пример #21
0
 public static string GetStateBadgeColor(JobState state)
 {
     return(state switch
     {
         JobState.RanToCompletion => "badge badge-pill badge-success",
         JobState.Faulted => "badge badge-pill badge-danger",
         JobState.WaitingToRun => "badge badge-pill badge-primary",
         JobState.WaitingForChildrenToComplete => "badge badge-pill badge-secondary",
         JobState.Running => "badge badge-pill badge-info",
         JobState.Warning => "badge badge-pill badge-warning",
         _ => "badge badge-pill badge-light"
     });
        public PeekRequest(JobState state)
        {
            if (state != JobState.Ready &&
                state != JobState.Delayed &&
                state != JobState.Buried)
            {
                throw new ArgumentOutOfRangeException("Cannot peek jobs in state " + state.ToString());
            }

            _state = state;
            _id    = null;
        }
Пример #23
0
 internal void SetJobState(JobState state, Exception reason)
 {
     using (PowerShellTraceSource source = PowerShellTraceSourceFactory.GetTraceSource())
     {
         this.AssertNotDisposed();
         bool flag = false;
         System.Management.Automation.JobStateInfo stateInfo = this.stateInfo;
         lock (this.syncObject)
         {
             this.stateInfo = new System.Management.Automation.JobStateInfo(state, reason);
             if (state == JobState.Running)
             {
                 if (!this.PSBeginTime.HasValue)
                 {
                     this.PSBeginTime = new DateTime?(DateTime.Now);
                 }
             }
             else if (this.IsFinishedState(state))
             {
                 flag = true;
                 if (!this.PSEndTime.HasValue)
                 {
                     this.PSEndTime = new DateTime?(DateTime.Now);
                 }
             }
         }
         if (flag)
         {
             this.CloseAllStreams();
         }
         try
         {
             source.WriteMessage("Job", "SetJobState", Guid.Empty, this, "Invoking StateChanged event", null);
             this.StateChanged.SafeInvoke <JobStateEventArgs>(this, new JobStateEventArgs(this.stateInfo.Clone(), stateInfo));
         }
         catch (Exception exception)
         {
             source.WriteMessage("Job", "SetJobState", Guid.Empty, this, "Some Job StateChange event handler threw an unhandled exception.", null);
             source.TraceException(exception);
             CommandProcessorBase.CheckForSevereException(exception);
         }
         if (flag)
         {
             lock (this.syncObject)
             {
                 if (this.finished != null)
                 {
                     this.finished.Set();
                 }
             }
         }
     }
 }
Пример #24
0
 private void executeJob(JobState state, string details, Job job)
 {
     lock (_Logs)
     {
         _Logs.Add(new JobLog()
         {
             On = DateTime.Now,
             Title = "job named '" + job.Name + "' state is " + state,
             Details = details
         });
     }
 }
Пример #25
0
        private void PaperHandler_ReportFinished(object sender, PaperInfoFinishArgs e)
        {
            try
            {
                //one finished
                if (e.Error != null)
                {
                    //异常出错
                    lock (m_ErrorNumLock) { ErrorNum++; }
                    SLogger.Instance.Writer(SLogLevel.Error, e.Error.Code + e.Error.Msg);
                    return;
                }
                UserPaperDto u     = e.UPaper;
                string       uName = u.UserName;

                lock (m_HandledNumLock)
                {
                    //执行的成功次数
                    HandledNum++;
                }
                PaperInfoFinishArgs arg = new PaperInfoFinishArgs()
                {
                    UPaper = u
                };
                OnRaiseReporting(arg);

                //to remove
                if (m_HandlerDic.ContainsKey(uName))
                {
                    m_HandlerDic.Remove(uName);
                }
            }
            catch (Exception ex)
            {
                SLogger.Instance.Writer(SLogLevel.Error, e.Error.Code + e.Error.Msg);
            }
            finally
            {
                //todo next 轮询
                RunOneTask();
                lock (m_FinishLock)
                {
                    if (IsCompleted && !m_OneFinished)
                    {
                        m_OneFinished = true;
                        m_State       = JobState.End;
                        //finished
                        Console.WriteLine("All Finished!");
                        OnRaiseFinished(new EventArgs());
                    }
                }
            }
        }
Пример #26
0
        JobState GetJobState(JobKey key)
        {
            JobState job;

            if (!_dJobs.TryGetValue(key, out job))
            {
                job = new JobState();
                _dJobs.Add(key, job);
            }

            return(job);
        }
Пример #27
0
 internal async Task<QueryResult<Job>> FindJobs(string userId, int start, int limit, DateTime? fromDateTime, JobState jobStateToFetchUpTo, SortDirection sortByCreateTimeDirection)
 {
     var FindContext = fromDateTime == null ?
         _context.Jobs.Find(x => x.Assets.ContainsKey(userId) && x.State == jobStateToFetchUpTo) :
         _context.Jobs.Find(x => x.Assets.ContainsKey(userId) && x.State == jobStateToFetchUpTo && x.CreateTime >= fromDateTime);
     var orderContext = sortByCreateTimeDirection == SortDirection.Descending ? FindContext.SortByDescending(x => x.CreateTime) : FindContext.SortBy(x => x.CreateTime);
     return new QueryResult<Job>()
     {
         Total = await orderContext.CountAsync(),
         Result = await orderContext.Skip(start).Limit(limit).ToListAsync()                
     };
 }
Пример #28
0
        public bool CreateJob(string jobNumber)
        {
            if (IsJobOpen && SavePending)
            {
                ExitChoice choice = CMessageBox.ShowExitDialog("There are unsaved changes to the currently opened job. What would you like to do?",
                                                               "Confirm", System.Windows.Forms.MessageBoxButtons.OKCancel, Resources.warning_64x64, true);
                switch (choice)
                {
                case ExitChoice.SaveAndExit:
                {
                    isClosing = true;
                    Save();
                    break;
                }

                case ExitChoice.ExitNoSave:
                {
                    isClosing = true;
                    Close();
                    break;
                }

                case ExitChoice.SaveOnly:
                {
                    Save();
                    return(false);
                }

                case ExitChoice.Cancel:
                {
                    StatusUpdate?.Invoke(this, new StatusArgs("Creation of Job# " + jobNumber + " canceled."));
                    _jobState = JobState.CreateCancelled;
                    return(false);
                }
                }
            }

            _jobState = Create(jobNumber);
            if (_jobState == JobState.DuplicateJobNumber)
            {
                StatusUpdate?.Invoke(this, new StatusArgs($"Job# {jobNumber} already exists. Try opening it instead."));
                _jobState = JobState.DuplicateJobNumber;
                return(false);
            }

            if (CurrentJob != null)
            {
                _jobState = JobState.Opened;
            }

            return(true);
        }
Пример #29
0
        public JobInfo(Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job, bool hasAccess)
        {
            // ok for any user to see
            // these should only be seen if acls allow
            this.id = MRApps.ToString(job.GetID());
            JobReport report = job.GetReport();

            this.startTime   = report.GetStartTime();
            this.finishTime  = report.GetFinishTime();
            this.elapsedTime = Times.Elapsed(this.startTime, this.finishTime);
            if (this.elapsedTime == -1)
            {
                this.elapsedTime = 0;
            }
            this.name                  = job.GetName().ToString();
            this.user                  = job.GetUserName();
            this.state                 = job.GetState();
            this.mapsTotal             = job.GetTotalMaps();
            this.mapsCompleted         = job.GetCompletedMaps();
            this.mapProgress           = report.GetMapProgress() * 100;
            this.mapProgressPercent    = StringHelper.Percent(report.GetMapProgress());
            this.reducesTotal          = job.GetTotalReduces();
            this.reducesCompleted      = job.GetCompletedReduces();
            this.reduceProgress        = report.GetReduceProgress() * 100;
            this.reduceProgressPercent = StringHelper.Percent(report.GetReduceProgress());
            this.acls                  = new AList <ConfEntryInfo>();
            if (hasAccess)
            {
                this.diagnostics = string.Empty;
                CountTasksAndAttempts(job);
                this.uberized = job.IsUber();
                IList <string> diagnostics = job.GetDiagnostics();
                if (diagnostics != null && !diagnostics.IsEmpty())
                {
                    StringBuilder b = new StringBuilder();
                    foreach (string diag in diagnostics)
                    {
                        b.Append(diag);
                    }
                    this.diagnostics = b.ToString();
                }
                IDictionary <JobACL, AccessControlList> allacls = job.GetJobACLs();
                if (allacls != null)
                {
                    foreach (KeyValuePair <JobACL, AccessControlList> entry in allacls)
                    {
                        this.acls.AddItem(new ConfEntryInfo(entry.Key.GetAclName(), entry.Value.GetAclString
                                                                ()));
                    }
                }
            }
        }
Пример #30
0
 protected virtual void LogJob(JobState state,
                               JobInfo job,
                               Exception exception = null)
 {
     if (exception == null)
     {
         Log.Write("Jobs", "Job Success", ("JobName", job.Identifier));
     }
     else
     {
         Log.Write(exception, ("JobName", job.Identifier));
     }
 }
Пример #31
0
        /// <summary>
        /// GetJobsByState
        /// </summary>
        public override IList <Job2> GetJobsByState(JobState state, bool recurse)
        {
            List <Job2> rtnList = new List <Job2>();

            foreach (var job in _repository.Values)
            {
                if (job.JobStateInfo.State == state)
                {
                    rtnList.Add(job);
                }
            }
            return(rtnList);
        }
Пример #32
0
 protected virtual void LogJob(JobState state,
                               JobInfo job,
                               Exception?exception = null)
 {
     if (exception == null)
     {
         this.Log.LogInformation(state == JobState.Finish ? "Job Success" : $"Job {state}", ("JobName", job.Identifier));
     }
     else
     {
         this.Log.LogError(exception, "Error running job " + job.Identifier);
     }
 }
Пример #33
0
 protected virtual void LogJob(JobState state,
                               JobInfo job,
                               Exception?exception = null)
 {
     if (exception == null)
     {
         Log.Write("Jobs", state == JobState.Finish ? "Job Success" : $"Job {state}", ("JobName", job.Identifier));
     }
     else
     {
         Log.Write(exception, ("JobName", job.Identifier));
     }
 }
Пример #34
0
        private void HandleJobStateChanged(object sender, JobStateEventArgs e)
        {
            ThreadJob job   = sender as ThreadJob;
            JobState  state = e.JobStateInfo.State;

            if (state == JobState.Completed ||
                state == JobState.Stopped ||
                state == JobState.Failed)
            {
                job.StateChanged -= new EventHandler <JobStateEventArgs>(HandleJobStateChanged);
                DecrementCurrentJobs();
            }
        }
Пример #35
0
 private async Task AddJobToDb(JobState jobState)
 {
     var jobStore = Nebula.ComponentContext.GetComponent(typeof(IJobStore)) as IJobStore;
     await jobStore.AddOrUpdateDefinition(new JobData
     {
         TenantId = Tenant.Id,
         JobId    = _jobId,
         Status   = new JobStatusData {
             State = jobState
         },
         Configuration = new JobConfigurationData()
     });
 }
Пример #36
0
        /// <summary>
        /// Waits for the job specified by clusterArgs to finish. If the state is Canceled or Failed,
        /// will throw an exception. Attempts to connect to the cluster if not already connected.
        /// </summary>
        /// <param name="clusterArgs">cluster args</param>
        /// <param name="maxNumTimesToResubmitFailedTasks">max number of times to resubmit</param>
        public static void WaitForJob(ClusterSubmitterArgs clusterArgs, int maxNumTimesToResubmitFailedTasks = 0)
        {
            JobState jobState = WaitForJobInternal(clusterArgs, maxNumTimesToResubmitFailedTasks);

            if (jobState == Microsoft.Hpc.Scheduler.Properties.JobState.Canceled)
            {
                throw new Exception("Job canceled.");
            }
            else if (jobState == Microsoft.Hpc.Scheduler.Properties.JobState.Failed)
            {
                throw new Exception("Job failed.");
            }
        }
Пример #37
0
 public static string GenerateStateString(JobState state, string JobName)
 {
     switch (state)
     {
         case JobState.ENQUEUED:
             return string.Concat(JobName, " is enqueued");
         case JobState.IN_PROGRESS:
             return string.Concat(JobName, " is in progress");
         case JobState.COMPLETED:
             return string.Concat(JobName, " is completed");
         case JobState.CANCELLED:
             return string.Concat(JobName, " is cancelled");
         default:
             throw new InvalidOperationException("Invalid/Unsupported Job state provided");
     }
 }
Пример #38
0
 internal void DoSetJobState(JobState state, Exception reason = null)
 {
     if (!this._disposed)
     {
         try
         {
             this._tracer.WriteMessage("PSChildJobProxy", "DoSetJobState", Guid.Empty, this, "BEGIN Set job state to {0} and call event handlers", new string[] { state.ToString() });
             StructuredTracer.BeginProxyChildJobEventHandler(base.InstanceId);
             base.SetJobState(state, reason);
             StructuredTracer.EndProxyJobEventHandler(base.InstanceId);
             this._tracer.WriteMessage("PSChildJobProxy", "DoSetJobState", Guid.Empty, this, "END Set job state to {0} and call event handlers", new string[] { state.ToString() });
         }
         catch (ObjectDisposedException)
         {
         }
     }
 }
Пример #39
0
 /// <summary>
 /// Constructor from the API.
 /// </summary>
 /// <param name="src"></param>
 internal IndustryJob(SerializableJobListItem src)
 {
     m_state = GetState(src);
     m_jobID = src.JobID;
     m_installedItemID = src.InstalledItemTypeID;
     m_installedItem = StaticBlueprints.GetBlueprintByID(src.InstalledItemTypeID);
     m_outputItemID = src.OutputTypeID;
     m_outputItem = GetOutputItem(src.OutputTypeID);
     m_runs = src.Runs;
     m_activity = (BlueprintActivity) Enum.ToObject(typeof (BlueprintActivity), src.ActivityID);
     m_blueprintType = (BlueprintType) Enum.ToObject(typeof (BlueprintType), src.InstalledItemCopy);
     m_installation = GetInstallation(src.OutputLocationID);
     m_solarSystem = StaticGeography.GetSystem(src.SolarSystemID);
     m_installedTime = src.InstallTime;
     m_installedItemME = src.InstalledItemMaterialLevel;
     m_installedItemPE = src.InstalledItemProductivityLevel;
     m_beginProductionTime = src.BeginProductionTime;
     m_endProductionTime = src.EndProductionTime;
     m_pauseProductionTime = src.PauseProductionTime;
     m_lastStateChange = DateTime.UtcNow;
     m_issuedFor = src.IssuedFor;
     m_activeJobState = GetActiveJobState();
 }
Пример #40
0
        /// <summary>
        /// List jobs.
        /// </summary>
        /// <param name="resourceGroupName">Name of the resource group.</param>
        /// <param name="jobCollectionName">job collection name.</param>
        /// <param name="jobName">Name of the job.</param>
        /// <param name="jobState">State of the job.</param>
        /// <returns>List of Job definition.</returns>
        internal IList<JobDefinition> ListJobs(string resourceGroupName, string jobCollectionName, JobState? jobState)
        {
            var listOfJobs = new List<JobDefinition>();

            var oDataQuery = new ODataQuery<JobStateFilter>();

            if (jobState != null)
            {
                Expression<Func<JobStateFilter, bool>> jobFilterExpression = (jobStateFilter) => jobStateFilter.State == jobState;
                oDataQuery.SetFilter(jobFilterExpression);
            }

            IPage<JobDefinition> jobsPage = this.SchedulerManagementClient.Jobs.List(resourceGroupName, jobCollectionName, oDataQuery);

            listOfJobs.AddRange(jobsPage);

            while (!string.IsNullOrWhiteSpace(jobsPage.NextPageLink))
            {
                jobsPage = this.SchedulerManagementClient.Jobs.ListNext(jobsPage.NextPageLink);
                listOfJobs.AddRange(jobsPage);
            }

            return listOfJobs;
        }
Пример #41
0
 /// <summary>
 /// Constructor from an object deserialized from the settings file.
 /// </summary>
 /// <param name="src"></param>
 internal IndustryJob(SerializableJob src)
 {
     m_ignored = src.Ignored;
     m_jobID = src.JobID;
     m_state = src.State;
     m_installedItemID = src.InstalledItemID;
     m_installedItem = StaticBlueprints.GetBlueprintByID(src.InstalledItemID);
     m_outputItemID = src.OutputItemID;
     m_outputItem = GetOutputItem(src.OutputItemID);
     m_runs = src.Runs;
     m_activity = src.Activity;
     m_blueprintType = src.BlueprintType;
     m_installation = src.ItemLocation;
     m_solarSystem = StaticGeography.GetSystem(src.SolarSystemID);
     m_installedTime = src.InstalledTime;
     m_installedItemME = src.InstalledItemME;
     m_installedItemPE = src.InstalledItemPE;
     m_beginProductionTime = src.BeginProductionTime;
     m_endProductionTime = src.EndProductionTime;
     m_pauseProductionTime = src.PauseProductionTime;
     m_lastStateChange = src.LastStateChange;
     m_issuedFor = src.IssuedFor;
     m_activeJobState = GetActiveJobState();
 }
 private static bool IsFinalJobState(JobState jobState)
 {
     return (jobState == JobState.Canceled) || (jobState == JobState.Error) || (jobState == JobState.Finished);
 }
        public static void WaitForJob(string jobId, JobState jobState, Action<string> verifyAction, Action<double> progressChangedAction  = null)
        {
            DateTime start = DateTime.Now;
            while (true)
            {
                CloudMediaContext context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
                IJob job2 = context2.Jobs.Where(c => c.Id == jobId).Single();
                ITask jobtask = job2.Tasks.Where(t=> t.State == JobState.Processing).FirstOrDefault();

                if (jobtask != null && jobtask.Progress > 0 && jobtask.Progress <= 100)
                {
                  if (progressChangedAction != null)
                    {
                        progressChangedAction(jobtask.Progress);
                    }
                }
                if (job2.State == jobState)
                {
                    verifyAction(jobId);
                    return;
                }
                if (job2.State == JobState.Error)
                {
                    StringBuilder str = new StringBuilder();
                    str.AppendFormat("Job should not fail - Current State = {0} Expected State = {1} jobId = {2}", job2.State, jobState, jobId);
                    str.AppendLine();
                    foreach (var task in job2.Tasks)
                    {
                        foreach (var error in task.ErrorDetails)
                        {
                            str.AppendFormat("Error Code: {0} ErrorMessage: {1}", error.Code, error.Message);
                            str.AppendLine();
                        }
                    }

                    throw new Exception(str.ToString());
                }

                if (DateTime.Now - start > TimeSpan.FromMinutes(JobTimeOutInMinutes))
                {
                    throw new Exception("Job Timed out - Current State " + job2.State.ToString() + " Expected State " + jobState + " jobId = " + jobId);
                }
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }
Пример #44
0
 /// <summary>
 /// Get list of jobs that are in the specified state
 /// </summary>
 /// <param name="state">state to match</param>
 /// <param name="recurse"></param>
 /// <returns>collection of jobs with the specified
 /// state</returns>
 public abstract IList<Job2> GetJobsByState(JobState state, bool recurse);
 /// <summary>
 /// Initializes a new instance of the JobListWithFilterParameters class
 /// with required arguments.
 /// </summary>
 public JobListWithFilterParameters(JobState state)
     : this()
 {
     this.State = state;
 }
Пример #46
0
        public static void IncrementWorkflowStateData(Guid parentJobInstanceId, JobState state)
        {
            if (isWinSQMEnabled)
            {
                lock (syncObject)
                {
                    int num;
                    int num2;
                    int num3;
                    int num4;
                    if (workflowStateData.ContainsKey(parentJobInstanceId))
                    {
                        Tuple<int, int, int, int> tuple = workflowStateData[parentJobInstanceId];
                        num = tuple.Item1;
                        if (num != 0)
                        {
                            num2 = tuple.Item2;
                            num3 = tuple.Item3;
                            num4 = tuple.Item4;
                            switch (state)
                            {
                                case JobState.Completed:
                                    num2++;
                                    goto Label_008A;

                                case JobState.Failed:
                                    num3++;
                                    goto Label_008A;

                                case JobState.Stopped:
                                    num4++;
                                    goto Label_008A;
                            }
                        }
                    }
                    goto Label_00B1;
                Label_008A:
                    num--;
                    workflowStateData[parentJobInstanceId] = new Tuple<int, int, int, int>(num, num2, num3, num4);
                Label_00B1:;
                }
            }
        }
Пример #47
0
        public void UpdateJob_ResetsTheJobStateAppropriately(JobState initialJobState, JobState expectedJobState)
        {
            Mocks.ReplayAll();

            // Create a job in the specified initial state.
            JobDetails job = CreatePendingJob("job", DateTime.UtcNow);
            job.JobState = initialJobState;
            jobStore.SaveJobDetails(job);

            // Update it.
            jobStore.UpdateJob("job", job.JobSpec);

            // Ensure its state has been updated appropriately.
            JobDetails updatedJob = jobStore.GetJobDetails("job");
            Assert.AreEqual(expectedJobState, updatedJob.JobState);
        }
Пример #48
0
        public void SchedulerHandlesUnexpectedJobStateReceivedFromWatcherByStoppingTheTrigger(JobState jobState)
        {
            JobDetails jobDetails = new JobDetails(dummyJobSpec, DateTime.UtcNow);
            jobDetails.JobState = jobState;

            PrepareMockJobWatcher(jobDetails);

            mockJobStore.SaveJobDetails(jobDetails);
            LastCall.Do((SaveJobDetailsDelegate) WakeOnSaveJobDetails);

            Mocks.ReplayAll();

            RunSchedulerUntilWake();

            Assert.AreEqual(JobState.Stopped, jobDetails.JobState);
            Assert.IsNull(jobDetails.NextTriggerFireTimeUtc);
            Assert.IsNull(jobDetails.NextTriggerMisfireThreshold);
            Assert.IsNull(jobDetails.LastJobExecutionDetails);
            Assert.IsNull(jobDetails.JobSpec.JobData);
        }
Пример #49
0
		internal StatusInfo(Guid instanceId, string name, string location, string command, string statusMessage, JobState jobState, bool hasMoreData, DateTime? startTime, DateTime? stopTime, ScheduledJobDefinition definition)
		{
			if (definition != null)
			{
				this._instanceId = instanceId;
				this._name = name;
				this._location = location;
				this._command = command;
				this._statusMessage = statusMessage;
				this._jobState = jobState;
				this._hasMoreData = hasMoreData;
				this._startTime = startTime;
				this._stopTime = stopTime;
				this._definition = definition;
				return;
			}
			else
			{
				throw new PSArgumentNullException("definition");
			}
		}
Пример #50
0
 private void CheckIfMonitoredJobIsComplete(Job job, JobState jobState)
 {
     if (job.IsFinishedState(jobState))
     {
         lock (this._myLock)
         {
             this.StopMonitoringJob(job);
         }
     }
 }
Пример #51
0
		public override IList<Job2> GetJobsByState(JobState state, bool recurse)
		{
			this.RefreshRepository();
			List<Job2> job2s = new List<Job2>();
			foreach (Job2 job in ScheduledJobSourceAdapter.JobRepository.Jobs)
			{
				if (state != job.JobStateInfo.State)
				{
					continue;
				}
				job2s.Add(job);
			}
			return job2s;
		}
Пример #52
0
		private StatusInfo(SerializationInfo info, StreamingContext context)
		{
			if (info != null)
			{
				this._instanceId = Guid.Parse(info.GetString("Status_InstanceId"));
				this._name = info.GetString("Status_Name");
				this._location = info.GetString("Status_Location");
				this._command = info.GetString("Status_Command");
				this._statusMessage = info.GetString("Status_Message");
				this._jobState = (JobState)info.GetValue("Status_State", typeof(JobState));
				this._hasMoreData = info.GetBoolean("Status_MoreData");
				this._definition = (ScheduledJobDefinition)info.GetValue("Status_Definition", typeof(ScheduledJobDefinition));
				DateTime dateTime = info.GetDateTime("Status_StartTime");
				if (dateTime == DateTime.MinValue)
				{
					this._startTime = null;
				}
				else
				{
					this._startTime = new DateTime?(dateTime);
				}
				DateTime dateTime1 = info.GetDateTime("Status_StopTime");
				if (dateTime1 == DateTime.MinValue)
				{
					this._stopTime = null;
					return;
				}
				else
				{
					this._stopTime = new DateTime?(dateTime1);
					return;
				}
			}
			else
			{
				throw new PSArgumentNullException("info");
			}
		}
Пример #53
0
 internal static bool ComputeJobStateFromChildJobStates(string traceClassName, JobStateEventArgs e, ref int blockedChildJobsCount, ref int suspendedChildJobsCount, ref int suspendingChildJobsCount, ref int finishedChildJobsCount, ref int failedChildJobsCount, ref int stoppedChildJobsCount, int childJobsCount, out JobState computedJobState)
 {
     computedJobState = JobState.NotStarted;
     using (PowerShellTraceSource source = PowerShellTraceSourceFactory.GetTraceSource())
     {
         if (e.JobStateInfo.State == JobState.Blocked)
         {
             Interlocked.Increment(ref blockedChildJobsCount);
             source.WriteMessage(traceClassName, ": JobState is Blocked, at least one child job is blocked.");
             computedJobState = JobState.Blocked;
             return true;
         }
         if (e.PreviousJobStateInfo.State == JobState.Blocked)
         {
             Interlocked.Decrement(ref blockedChildJobsCount);
             if (blockedChildJobsCount == 0)
             {
                 source.WriteMessage(traceClassName, ": JobState is unblocked, all child jobs are unblocked.");
                 computedJobState = JobState.Running;
                 return true;
             }
             return false;
         }
         if (e.PreviousJobStateInfo.State == JobState.Suspended)
         {
             Interlocked.Decrement(ref suspendedChildJobsCount);
         }
         if (e.PreviousJobStateInfo.State == JobState.Suspending)
         {
             Interlocked.Decrement(ref suspendingChildJobsCount);
         }
         if (e.JobStateInfo.State == JobState.Suspended)
         {
             Interlocked.Increment(ref suspendedChildJobsCount);
             if ((suspendedChildJobsCount + finishedChildJobsCount) == childJobsCount)
             {
                 source.WriteMessage(traceClassName, ": JobState is suspended, all child jobs are suspended.");
                 computedJobState = JobState.Suspended;
                 return true;
             }
             return false;
         }
         if (e.JobStateInfo.State == JobState.Suspending)
         {
             Interlocked.Increment(ref suspendingChildJobsCount);
             if (((suspendedChildJobsCount + finishedChildJobsCount) + suspendingChildJobsCount) == childJobsCount)
             {
                 source.WriteMessage(traceClassName, ": JobState is suspending, all child jobs are in suspending state.");
                 computedJobState = JobState.Suspending;
                 return true;
             }
             return false;
         }
         if (((e.JobStateInfo.State != JobState.Completed) && (e.JobStateInfo.State != JobState.Failed)) && (e.JobStateInfo.State != JobState.Stopped))
         {
             if (e.JobStateInfo.State == JobState.Running)
             {
                 computedJobState = JobState.Running;
                 return true;
             }
             return false;
         }
         if (e.JobStateInfo.State == JobState.Failed)
         {
             Interlocked.Increment(ref failedChildJobsCount);
         }
         if (e.JobStateInfo.State == JobState.Stopped)
         {
             Interlocked.Increment(ref stoppedChildJobsCount);
         }
         bool flag = false;
         int num = Interlocked.Increment(ref finishedChildJobsCount);
         if (num == childJobsCount)
         {
             flag = true;
         }
         if (flag)
         {
             if (failedChildJobsCount > 0)
             {
                 source.WriteMessage(traceClassName, ": JobState is failed, at least one child job failed.");
                 computedJobState = JobState.Failed;
                 return true;
             }
             if (stoppedChildJobsCount > 0)
             {
                 source.WriteMessage(traceClassName, ": JobState is stopped, stop is called.");
                 computedJobState = JobState.Stopped;
                 return true;
             }
             source.WriteMessage(traceClassName, ": JobState is completed.");
             computedJobState = JobState.Completed;
             return true;
         }
         if ((suspendedChildJobsCount + num) == childJobsCount)
         {
             source.WriteMessage(traceClassName, ": JobState is suspended, all child jobs are suspended.");
             computedJobState = JobState.Suspended;
             return true;
         }
         if (((suspendingChildJobsCount + suspendedChildJobsCount) + num) == childJobsCount)
         {
             source.WriteMessage(traceClassName, ": JobState is suspending, all child jobs are in suspending state.");
             computedJobState = JobState.Suspending;
             return true;
         }
     }
     return false;
 }
 /// <summary>
 /// Initializes a new instance of the
 /// JobCollectionJobsUpdateStateParameters class with required
 /// arguments.
 /// </summary>
 public JobCollectionJobsUpdateStateParameters(JobState state)
     : this()
 {
     this.State = state;
 }
        /// <summary>
        /// Waits for expected job state and updates job priority.
        /// </summary>
        /// <param name="job">The job.</param>
        /// <param name="expectedJobState">Expected state of the job.</param>
        /// <param name="newPriority">The new priority.</param>
        private void WaitForJobStateAndUpdatePriority(IJob job, JobState expectedJobState, int newPriority)
        {
            WaitForJob(job.Id, expectedJobState, (string id) => { });

            job = _mediaContext.Jobs.Where(c => c.Id == job.Id).FirstOrDefault();
            Assert.IsNotNull(job);
            Assert.AreEqual(InitialJobPriority, job.Priority);
            job.Priority = newPriority;
            job.Update();

            job = _mediaContext.Jobs.Where(c => c.Id == job.Id).FirstOrDefault();
            Assert.IsNotNull(job);
            Assert.AreEqual(newPriority, job.Priority, "Job Priority is not matching expected value");
        }
Пример #56
0
        public async Task<IHttpActionResult> GetAssignedJobs(string userId = null, int pageSize = AppConstants.DefaultPageSize, int page = 0, string fromDateTime = null, JobState jobStateUpto = JobState.IN_PROGRESS, SortDirection sortDirection = SortDirection.Descending)
        {
            DateTime? fromdt = null;
            if (!string.IsNullOrEmpty(fromDateTime))
            {
                fromdt = DateTime.Parse(fromDateTime);
            }
            if (!string.IsNullOrWhiteSpace(userId))
            {
                if (this.User.IsInRole("Asset") && (this.User.Identity.GetUserId() != userId))
                    return Content(HttpStatusCode.Forbidden, "Accessing Assigned jobs of other Assets is not supported unless you're an admin");
            }
            else
            {
                userId = this.User.Identity.GetUserId();
            }

            var result = await accountContext.FindAssignedJobs(userId, page, pageSize, fromdt, jobStateUpto, sortDirection, this.Request);
            return Ok(result);
        }
Пример #57
0
 private void AssertValidState(JobState expectedState)
 {
     AssertNotDisposed();
     lock (SyncRoot)
     {
         if (JobStateInfo.State != expectedState)
         {
             throw new InvalidJobStateException(JobStateInfo.State, Resources.JobCannotBeStarted);
         }
     }
 }
 /// <summary>
 /// Initializes a new instance of the JobUpdateStateParameters class
 /// with required arguments.
 /// </summary>
 public JobUpdateStateParameters(JobState state)
     : this()
 {
     this.State = state;
 }
Пример #59
0
        /// <summary>
        /// 执行任务
        /// </summary>
        public void Execute()
        {
            while (true)
            {
                if (this.IsRun() && this._State == JobState.Running)
                {
                    //记录最近执行时间
                    _LatestRunTime = DateTime.Now.ToString();

                    try
                    {
                        WriteLog(string.Format("正在执行任务[{0}]......", this.Name), LogType.Information);

                        //执行任务
                        Type type = Type.GetType(string.Format("{0}, {1}", _ClassName, _AssemblyName));
                        object obj = Activator.CreateInstance(type);
                        ITask task = obj as ITask;
                        task.Run();

                        WriteLog(string.Format("执行任务[{0}]成功!", this.Name), LogType.Information);
                    }
                    catch (Exception ex)
                    {
                        if (_IsStopIfException)
                        {
                            _State = JobState.Stop;
                            TaskThreadPool.Instance.Threads[_Name].Abort();
                        }

                        _ExceptionCount = _ExceptionCount + 1;
                        _LatestException = new MySoftException(ExceptionType.TaskException, "Task任务执行失败!", ex);

                        WriteLog(string.Format("执行任务[{0}]失败,错误:{1}!", this.Name, ex.Message), LogType.Error);
                    }
                }

                Thread.Sleep(_Interval);
            }
        }
Пример #60
0
 private JobStatus MapWamsJobState(JobState state) {
     switch (state) {
         case JobState.Canceled:
             return JobStatus.Canceled;
         case JobState.Canceling:
             return JobStatus.Canceling;
         case JobState.Error:
             return JobStatus.Faulted;
         case JobState.Finished:
             return JobStatus.Finished;
         case JobState.Processing:
             return JobStatus.Processing;
         case JobState.Queued:
             return JobStatus.Queued;
         case JobState.Scheduled:
             return JobStatus.Scheduled;
         default:
             return JobStatus.Pending;
     }
 }