Exemplo n.º 1
0
        private void IterateWorkflow(WorkflowRun <TWfContext> run)
        {
            if (_finish.Exists(precondition => precondition.Met(run.FinishedTasks)))
            {
                WorkflowFinished?.Invoke(this, new WorkflowEventArgs <TWfContext>(run.RunId, run.Context));
                return;
            }

            var tasksToExecute = _tasks.Where(kv => kv.Value.Met(run.FinishedTasks) && !run.HasFinished(kv.Key))
                                 .Select(kv => kv.Key).ToList();

            var anythingFinished = false;

            foreach (var task in tasksToExecute)
            {
                task.Action(run.Context);
                run.StartTask(task);
                TaskStarted?.Invoke(this, new WorkflowTaskEventArgs <TWfContext>(run.RunId, task.TaskId, run.Context));
                if (task.Autocomplete)
                {
                    TaskFinished?.Invoke(this,
                                         new WorkflowTaskEventArgs <TWfContext>(run.RunId, task.TaskId, run.Context));
                    run.FinishTask(task);
                    anythingFinished = true;
                }
            }

            if (anythingFinished)
            {
                IterateWorkflow(run);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 开始下载任务
        /// </summary>
        public void Start()
        {
            lock (_external_lock)
            {
                lock (_thread_flag_lock)
                {
                    //clear error flag
                    _download_thread_flag = _download_thread_flag & ~_DOWNLOAD_THREAD_FLAG_ERROR;

                    if (((_download_thread_flag & 0xffffff) & (_DOWNLOAD_THREAD_FLAG_READY | _DOWNLOAD_THREAD_FLAG_PAUSED)) != 0)
                    {
                        //Tracer.GlobalTracer.TraceInfo("---STARTED---");
                        _download_thread_flag    = (_download_thread_flag | _DOWNLOAD_THREAD_FLAG_START_REQUESTED) & ~_DOWNLOAD_THREAD_FLAG_READY;
                        _url_fail_to_fetch_count = 0;
                        //_api.GetAccount(_data.AccountID).GetLocateDownloadLinkAsync(_data.Path, _main_url_request_callback);
                        _url_expire_time             = DateTime.Now;
                        _monitor_thread              = new Thread(_monitor_thread_callback);
                        _monitor_thread.Name         = "Download Monitor";
                        _monitor_thread.IsBackground = false;
                        _monitor_thread.Start();
                    }
                }
            }
            try { TaskStarted?.Invoke(this, new EventArgs()); }
            catch { }
        }
Exemplo n.º 3
0
 private void SetCurrentTask(AIBackupUnitTask task)
 {
     currentTask           = task;
     currentTask.Finished += OnCurrentTaskFinished;
     currentTask.Start();
     TaskStarted?.Invoke(currentTask);
 }
Exemplo n.º 4
0
        public void Update()
        {
            _searchItems.Clear();

            var classNames = ClassNames.ToList();
            var i          = 0;
            var n          = classNames.Count;
            var progress   = new Progress <ProgressInfo>();

            TaskStarted?.Invoke(progress);

            var progressInterface = (IProgress <ProgressInfo>)progress;

            _searchItems.AddRange(
                classNames
                .Select(
                    name => {
                var subKey   = _clsidKey.OpenSubKey(name);
                var regClass = subKey != default ? CreateSearchItem(new RegistryClass(subKey)) : default;
                progressInterface.Report(new ProgressInfo("Load Classes", ++i, n));
                return(regClass);
            }
                    )
                );
            OnPropertyChanged(nameof(Items));
        }
Exemplo n.º 5
0
        public void Start()
        {
            lock (_external_lock)
            {
                lock (_thread_flag_lock)
                {
                    //clearing attributed status
                    _upload_thread_flag = _upload_thread_flag & 0xffffff;
                    if ((_upload_thread_flag & (_UPLOAD_THREAD_FLAG_READY | _UPLOAD_THREAD_FLAG_PAUSED)) != 0)
                    {
                        if (_enable_slice_upload)
                        {
                            Tracer.GlobalTracer.TraceInfo("---STARTED---");
                            _upload_thread_flag = (_upload_thread_flag | _UPLOAD_THREAD_FLAG_START_REQUESTED) & ~_UPLOAD_THREAD_FLAG_READY;

                            //_monitor_thread = new Thread(_monitor_thread_callback);
                            //_monitor_thread.IsBackground = true;
                            //_monitor_thread.Name = "Upload monitor";
                            //_monitor_thread.Start();
                            ThreadPool.QueueUserWorkItem(new WaitCallback(_monitor_thread_callback), null);
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
                    else
                    {
                        return;
                    }
                }
            }
            try { TaskStarted?.Invoke(this, new EventArgs()); } catch { }
        }
Exemplo n.º 6
0
 public void OnTaskStarted(TaskDefinition task)
 {
     TaskStarted?.Invoke(new TaskStartedEvent
     {
         Task      = task,
         Timestamp = DateTimeUtils.Now
     });
 }
Exemplo n.º 7
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <exception cref="NotImplementedException"></exception>
        public void ExecuteTask(IEngineTask task)
        {
            // Check if task can be executed
            if (!task.CanBeExecuted())
            {
                task.AddMessage($"The task cannot be executed.", MessageSeverity.Error);
                if (task.ParentJob.FailIfAnyTaskHasError)
                {
                    throw new EngineException(logger, $"The task  cannot be executed. This job was aborted.");
                }
                else
                {
                    return;
                }
            }

            // Execute task
            if (TaskStarted != null)
            {
                TaskStarted.Invoke((Guid)task.EntityId, (Guid)task.InstanceID);
            }
            task.Start();

            // Stop task
            task.Stop();


            if (task.HasErrors)
            {
                task.AddMessage($"The task (instance: {task.InstanceID}) was not executed cause one or more errors occurs.", MessageSeverity.Error);
                if (task.ParentJob.FailIfAnyTaskHasError)
                {
                    if (TaskFinished != null)
                    {
                        TaskFinished.Invoke((Guid)task.EntityId, (Guid)task.InstanceID, false);
                    }

                    throw new EngineException(logger, $"The task (instance: {task.InstanceID}) was not executed cause one or more errors occurs. This job was aborted.");
                }
            }
            else if (task.HasWarnings)
            {
                task.AddMessage($"The task (instance: {task.InstanceID}) was executed but one or more warning occurs.", MessageSeverity.Warning);
                if (task.ParentJob.FailIfAnyTaskHasWarning)
                {
                    if (TaskFinished != null)
                    {
                        TaskFinished.Invoke((Guid)task.EntityId, (Guid)task.InstanceID, false);
                    }

                    throw new EngineException(logger, $"The task (instance: {task.InstanceID}) was executed but one or more warning occurs. This job was aborted.");
                }
            }
            if (TaskFinished != null)
            {
                TaskFinished.Invoke((Guid)task.EntityId, (Guid)task.InstanceID, true);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Raise one of the events that is appropriate for the type of the BuildEventArgs
        /// </summary>
        public void Dispatch(BuildEventArgs buildEvent)
        {
            if (buildEvent is BuildMessageEventArgs)
            {
                MessageRaised?.Invoke(null, (BuildMessageEventArgs)buildEvent);
            }
            else if (buildEvent is TaskStartedEventArgs)
            {
                TaskStarted?.Invoke(null, (TaskStartedEventArgs)buildEvent);
            }
            else if (buildEvent is TaskFinishedEventArgs)
            {
                TaskFinished?.Invoke(null, (TaskFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is TargetStartedEventArgs)
            {
                TargetStarted?.Invoke(null, (TargetStartedEventArgs)buildEvent);
            }
            else if (buildEvent is TargetFinishedEventArgs)
            {
                TargetFinished?.Invoke(null, (TargetFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is ProjectStartedEventArgs)
            {
                ProjectStarted?.Invoke(null, (ProjectStartedEventArgs)buildEvent);
            }
            else if (buildEvent is ProjectFinishedEventArgs)
            {
                ProjectFinished?.Invoke(null, (ProjectFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is BuildStartedEventArgs)
            {
                BuildStarted?.Invoke(null, (BuildStartedEventArgs)buildEvent);
            }
            else if (buildEvent is BuildFinishedEventArgs)
            {
                BuildFinished?.Invoke(null, (BuildFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is CustomBuildEventArgs)
            {
                CustomEventRaised?.Invoke(null, (CustomBuildEventArgs)buildEvent);
            }
            else if (buildEvent is BuildStatusEventArgs)
            {
                StatusEventRaised?.Invoke(null, (BuildStatusEventArgs)buildEvent);
            }
            else if (buildEvent is BuildWarningEventArgs)
            {
                WarningRaised?.Invoke(null, (BuildWarningEventArgs)buildEvent);
            }
            else if (buildEvent is BuildErrorEventArgs)
            {
                ErrorRaised?.Invoke(null, (BuildErrorEventArgs)buildEvent);
            }

            AnyEventRaised?.Invoke(null, buildEvent);
        }
Exemplo n.º 9
0
 public void StartTask()
 {
     GameManager.currentProgressor = this;
     Doozy.Engine.GameEventMessage.SendEvent(targetData.puzzleEventName);
     evt_taskStarted.Invoke(this);
     if (disablePlayerMovement)
     {
         GameManager.instance.EnablePlayerControl(false);
     }
 }
Exemplo n.º 10
0
        public void OnTaskStarted(EventArgs args)
        {
            groupBoxReadMode.Enabled = false;
            groupBoxSettings.Enabled = false;
            groupBoxTemp.Enabled     = false;
            buttonAbort.Enabled      = true;
            buttonPause.Enabled      = true;
            buttonSave.Enabled       = false;

            Paused.Set(); // set running/resumed
            TaskStarted?.Invoke(this, args);
        }
Exemplo n.º 11
0
        public void StartTask(BuildNode node)
        {
            _logger.LogDebug($"BuildProcess.StartTask: Node: \"{node.Name}\"");
            var task = FindTask(node);

            if (task != null)
            {
                _logger.LogDebug($"BuildProcess.StartTask: Task: {task.GetHashCode()}");
                CurrentTasks.Add(task);
                task.Start();
                TaskStarted?.Invoke(task);
            }
        }
Exemplo n.º 12
0
        public async Task RunTaskAsync(string title, Action <CancellationToken, IProgress <int> > task, Action <int> progressUpdate, Action taskCompleted)
        {
            if (_task != null)
            {
                throw new Exception("A task is already running.");
            }

            cancellationTokenSource = new CancellationTokenSource();
            cancellationToken       = cancellationTokenSource.Token;

            TaskStarted?.Invoke(this, null);

            _progressDialog = new ProgressDialog(this, _owner, $"Task - {title}", Maximum, Interval);
            _progressDialog.Show();

            var progress = new Progress <int>(percent =>
            {
                progressUpdate(percent);
            });

            try
            {
                _task = Task.Run(() =>
                {
                    task(cancellationToken, progress);
                }, cancellationToken);

                // wait for worker task to finish.
                await _task;
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine("Task cancelled.");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

            SystemSounds.Beep.Play();

            taskCompleted();

            _progressDialog.Close();

            TaskCompleted?.Invoke(this, null);

            _progressDialog = null;
            _task           = null;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Starts new task in current session
        /// </summary>
        /// <param name="context">The task context to start</param>
        private void StartNextTask(TimeTaskContext context)
        {
            // Set provided time
            CurrentTimeLeft = context.SessionDynamicTime;

            // Save it for progress calculations
            mCurrentTask.SessionDynamicTime = CurrentTimeLeft;

            // Start the timer
            mSecondsTicker.Start();

            // Inform subscribers
            TaskStarted.Invoke();
        }
Exemplo n.º 14
0
 public RepetitiveTask(Action action, int dueTime, int period)
 {
     State        = RepeririveTaskState.Stopped;
     DueTime      = dueTime;
     Period       = period;
     _action      = action;
     TaskStarted += (task) => State = RepeririveTaskState.TaskStarted;
     TaskEnded   += (task, status) => State = State != RepeririveTaskState.Stopped ? RepeririveTaskState.Waiting : State;
     _timer       = new Timer((sender) =>
     {
         TaskStarted?.Invoke(this);
         Task.Factory.StartNew(action).ContinueWith((task) =>
         {
             TaskEnded?.Invoke(this, task.Status);
         });
     }, null, Timeout.Infinite, Timeout.Infinite);
 }
Exemplo n.º 15
0
        private void StartTask(IScheduledTask scheduledTask)
        {
            Task        task        = null;
            RunningTask runningTask = null;

            lock (_lock)
            {
                if (!IsEnabled)
                {
                    return;
                }

                Log.Debug($"Starting task {scheduledTask}");

                runningTask = new RunningTask(scheduledTask, _timeService.CurrentDateTime);

#pragma warning disable 4014
                // Note: don't await, we are a scheduler
                task = TaskShim.Run(async() => await scheduledTask.InvokeAsync(), runningTask.CancellationTokenSource.Token);
                task.ContinueWith(OnRunningTaskCompleted);
#pragma warning restore 4014

                Log.Debug($"Started task {scheduledTask}");
            }

            if (!scheduledTask.ScheduleRecurringTaskAfterTaskExecutionHasCompleted)
            {
                // Schedule immediately, even though task is still running
                RescheduleRecurringTask(runningTask);
            }

            var completed = task.IsCompleted;
            if (completed)
            {
                // Shortcut mode
                TaskStarted?.Invoke(this, new TaskEventArgs(runningTask));

                OnRunningTaskCompleted(task);
            }
            else
            {
                _runningTasks.Add(new RunningTaskInfo(task, runningTask));

                TaskStarted?.Invoke(this, new TaskEventArgs(runningTask));
            }
        }
Exemplo n.º 16
0
        public void Confirm()
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    TaskEx.Delay(5000, _cancellationTokenSource.Token).GetAwaiter().GetResult();
                    if (_cancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }
                }
                catch (TaskCanceledException)
                {
                    return;
                }

                TaskStarted?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>(_taskData));
            });
        }
Exemplo n.º 17
0
        /// <summary>
        /// Checks the queue for new tasks and pops the next available task
        /// </summary>
        private void PopQueue()
        {
            if (!IsEnabled)
            {
                return;
            }

            lock (_taskQueue)
            {
                Task = null;

                if (!_taskQueue.Any())
                {
                    return;
                }

                Task = _taskQueue[0];
                _taskQueue.RemoveAt(0);
            }

            // Start a thread to execute the task
            _taskFactory.StartNew(() =>
            {
                // Reset values
                IsAbortPending = false;
                TaskStarted?.Invoke(this, new TaskEventArgs(Task));
                ResetStatus();
                Logger.Record($"Executing task {Task.Type} for {Task.ModID}");

                // Execute task
                bool result = ExecuteTask();

                // Reset values
                ResetStatus();
                Logger.Record($"Task executed {(result ? "successfully" : "unsuccessfully")}");
                TaskEnded?.Invoke(this, new TaskEndedEventArgs(Task, result));

                // Pop queue again
                PopQueue();
            });
        }
Exemplo n.º 18
0
        public void RunTask()
        {
            if (!readyToGo)
            {
                throw new ArgumentException("Not ready to go!");
            }
            else
            {
                if (TaskStarted != null)
                {
                    TaskStarted.Invoke(this, new EventArgs());
                }
            }

            Active = true;

            Status = "Analyzing source";

            var urlGen = SetupTask();

            var urls = urlGen.Get(0, NumberToDownload);

            using (repo = new Repository()) {
                // pass on the events
                repo.DownloadFileCompleted += OnSingleDownloadCompleted;

                repo.DownloadProgressChanged += OnDownloadProgressChanged;

                repo.MultipleDownloadsCompleted += OnMultipleDownloadsCompleted;

                // set number downloaded to zero
                NumberDownloaded = 0;

                // begin (blocks)
                repo.Download(urls);
                // repo.Active is set and unset automatically
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// 启动服务
 /// </summary>
 public async Task Start()
 {
     cts = new CancellationTokenSource();
     await Task.Run(() =>
     {
         int times = 0;
         TaskStarted?.Invoke(this, new TaskEventArgs(TaskName));
         while (!cts.Token.IsCancellationRequested)
         {
             times++;
             if (times *Interval >= TaskCheckInterval)
             {
                 Log.Information($"{TaskName}正在运行");
                 times = 0;
             }
             Repository = new AppRepository();
             lastTime   = DateTime.Now;
             try
             {
                 Run();
             }
             catch (Exception ex)
             {
                 Log.Error(ex, $"{TaskName}抛出异常");
             }
             try
             {
                 Task.Delay(Interval).Wait(cts.Token);
             }
             catch (OperationCanceledException)
             {
             }
         }
         Log.Warning($"{TaskName}已取消");
         TaskStopped?.Invoke(this, new TaskEventArgs(TaskName));
     }, cts.Token);
 }
Exemplo n.º 20
0
 private void OnTaskStarted()
 {
     TaskStarted?.Invoke(this, new ObservableTaskEventArgs(_task));
 }
Exemplo n.º 21
0
 private void FireTaskStarted()
 {
     TaskStarted?.Invoke(this, EventArgs.Empty);
 }
Exemplo n.º 22
0
        private View ConstructView()
        {
            var outerLayout = new LinearLayout(_context)
            {
                Orientation = Orientation.Vertical
            };

            outerLayout.SetPadding(20, 0, 20, 10);

            var taskNameView = new TextView(_context);

            taskNameView.SetTextSize(Android.Util.ComplexUnitType.Pt, 9);

            if (TaskProgress != null)
            {
                if (TaskProgress.Status > Models.ProgressStatus.InProgress)
                {
                    taskNameView.Text = "✔ ";
                    outerLayout.SetBackgroundColor(Color.LightGreen);
                }
                else
                {
                    taskNameView.Text = "● ";
                    outerLayout.SetBackgroundColor(Color.LightYellow);
                }
            }
            else
            {
                taskNameView.Text = "○ ";
            }

            taskNameView.Text += Task.Name;

            var taskRegionLayout = new LinearLayout(_context)
            {
                Orientation = Orientation.Vertical,
                Visibility  = ViewStates.Gone
            };

            var taskDescTextView = new TextView(_context)
            {
                Text = Task.Description
            };

            taskDescTextView.SetTextSize(Android.Util.ComplexUnitType.Pt, 8);

            taskRegionLayout.AddView(taskDescTextView);

            if (ChallengeProgress?.Status == Models.ProgressStatus.InProgress)
            {
                if (TaskProgress == null)
                {
                    var taskBtn = new Button(_context);

                    taskBtn.SetBackgroundColor(Color.Orange);
                    taskBtn.Text = "Začít plnit úkol!";

                    taskBtn.Click += (o, e) =>
                    {
                        TaskProgress = new TaskProgress
                        {
                            Id                  = Guid.NewGuid(),
                            TaskId              = Task.Id,
                            LastModified        = DateTime.UtcNow,
                            ChallengeProgressId = ChallengeProgress.Id,
                            Status              = Models.ProgressStatus.InProgress
                        };

                        TaskStarted.Invoke(this, TaskProgress);
                        Invalidate();
                    };

                    taskRegionLayout.AddView(taskBtn);
                }
                else if (TaskProgress.Status == Models.ProgressStatus.InProgress)
                {
                    var taskBtn = new Button(_context);

                    taskBtn.SetBackgroundColor(Color.LightGreen);
                    taskBtn.Text = "Zažádat o potvrzení úkolu!";

                    taskBtn.Click += (o, e) =>
                    {
                        TaskConfirmationRequested.Invoke(this, TaskProgress);
                    };

                    taskRegionLayout.AddView(taskBtn);
                }
            }

            taskNameView.Click += (o, e) =>
            {
                if (taskRegionLayout.Visibility == ViewStates.Gone)
                {
                    taskRegionLayout.Visibility = ViewStates.Visible;
                }
                else
                {
                    taskRegionLayout.Visibility = ViewStates.Gone;
                }
            };

            outerLayout.AddView(taskNameView);
            outerLayout.AddView(taskRegionLayout);

            return(outerLayout);
        }
Exemplo n.º 23
0
 private void TaskRunner_TaskStarted(object sender, EventArgs e)
 {
     TaskStarted?.Invoke(sender, e);
 }
 // ReSharper disable once UnusedMember.Local
 private void OnTaskStarted(TaskStartedEventArgs e)
 {
     TaskStarted?.Invoke(this, e);
 }
Exemplo n.º 25
0
 private void RaiseTaskStarted(IBackgroundTask task, object state)
 => TaskStarted?.Invoke(task, state);
Exemplo n.º 26
0
 private void EventSourceOnTaskStarted(object sender, TaskStartedEventArgs e)
 {
     TaskStarted?.Invoke(sender, e);
 }
Exemplo n.º 27
0
        private async Task TaskLoop(CancellationToken ct)
        {
            try
            {
                while (!ct.IsCancellationRequested)
                {
                    State = NetworkServiceState.Finding;
                    var result = await _netService.WaitForOneConnection(ct);

                    var connection  = result.Key;
                    var commingType = result.Value;
                    var writer      = new BinaryWriter(connection.GetStream());
                    var reader      = new BinaryReader(connection.GetStream());

                    if (commingType == ConnectionCommingType.FromListen)
                    {
                        var jsontask = reader.ReadString();
                        var task     = JsonConvert.DeserializeObject <CreatedNetworkTaskData>(jsontask);
                        TaskCreated?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>(task));
                    }
                    else
                    {
                        //todo: generate task...
                        var task = new CreatedNetworkTaskData()
                        {
                            Frequency       = 33100,
                            FrequencyNumber = new Random().Next(0, 10),
                            Id = Guid.NewGuid()
                        };
                        var jsontask = JsonConvert.SerializeObject(task);
                        writer.Write(jsontask);
                        writer.Flush();
                        TaskCreated?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>(task));
                    }
                    State = NetworkServiceState.RequestForConfirm;

                    var remoteConfirm = TaskEx.Run(() =>
                    {
                        var confirmationResult = reader.ReadString();
                        var isConfirmed        = JsonConvert.DeserializeObject <ConfirmationResult>(confirmationResult);
                        return(isConfirmed);
                    });

                    var localConfirm = _completationConfirm.Task.ContinueWith(t =>
                    {
                        var cjs = JsonConvert.SerializeObject(t.Result);
                        writer.Write(cjs);
                        writer.Flush();
                        return(t.Result);
                    }, TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled);

                    var bothConfirmation = await TaskEx.WhenAll(remoteConfirm, localConfirm);

                    bool isBothConfimed = bothConfirmation.All(x => x.Result);
                    if (isBothConfimed)
                    {
                        TaskStarted?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>());
                    }
                    connection.Close();
                }
            }
            catch (TaskCanceledException) { }
            catch (Exception ex)
            {
                SimpleLogger.Log(ex);
            }
        }
Exemplo n.º 28
0
 //event callback
 #region event callback
 private void _on_task_started(object sender, EventArgs e)
 {
     try { TaskStarted?.Invoke(sender, e); }
     catch { }
 }
Exemplo n.º 29
0
        internal virtual void ProcessTask(ScheduledTask scheduledTask)
        {
            if (scheduledTask.IsQueued &&
                !scheduledTask.AllowMultipleInstance)
            {
                GlobalConfiguration.Logger.Warn("scheduled task {0} is in queue and not allow multiple instance", scheduledTask.Name);
                return;
            }

            if (!scheduledTask.AllowMultipleInstance)
            {
                if (TasksHost.IsRunning(scheduledTask.Name))
                {
                    GlobalConfiguration.Logger.Warn("scheduled task {0} is already running and not allow multiple instance", scheduledTask.Name);
                    return;
                }
            }

            var id = Guid.NewGuid();

            scheduledTask.IsQueued = true;

            TasksHost.Enqueue(
                id
                , scheduledTask.Name
                , scheduledTask.TaskType
                , scheduledTask.Parameters
                , (dic) =>
            {
                GlobalConfiguration.Logger.Info("scheduled task {0} completed", scheduledTask.Name);
                scheduledTask.IsQueued = false;
                try
                {
                    if (scheduledTask.Completed != null)
                    {
                        scheduledTask.Completed(dic);
                    }
                }
                catch (Exception ex)
                {
                    GlobalConfiguration.Logger.Error(ex);
                }
                finally
                {
                    scheduledTask.IsForced = false;
                    if (scheduledTask.NextRunningDateFactory != null)
                    {
                        try
                        {
                            scheduledTask.NextRunningDate = scheduledTask.NextRunningDateFactory.Invoke();
                        }
                        catch (Exception ex)
                        {
                            GlobalConfiguration.Logger.Error(ex);
                        }
                    }
                }
            }
                , (ex) =>
            {
                scheduledTask.Exception = ex;
                GlobalConfiguration.Logger.Error(ex);
                if (TaskFailed != null)
                {
                    try
                    {
                        TaskFailed.Invoke(scheduledTask.Name, ex);
                    }
                    catch { }
                }
            },
                null,
                () =>
            {
                GlobalConfiguration.Logger.Info("scheduled task {0} started", scheduledTask.Name);
                scheduledTask.StartedCount += 1;
                if (TaskStarted != null)
                {
                    try
                    {
                        TaskStarted.Invoke(scheduledTask.Name);
                    }
                    catch { }
                }
            },
                true,
                scheduledTask.IsForced);
        }
Exemplo n.º 30
0
 protected virtual void OnTaskStarted()
 {
     TaskStarted?.Invoke(this, EventArgs.Empty);
 }