示例#1
0
        static void ExecuteAllJob(int selectBranchId)
        {
            string currentDirectory = Environment.CurrentDirectory;

            foreach (var job in JobManager.Jobs)
            {
                if (selectBranchId > 0 && selectBranchId != job.Id)
                {
                    continue;
                }

                // 每次都切回程序目录,防止任务执行过程完没有切回来
                Environment.CurrentDirectory = currentDirectory;

                try {
                    if (s_enableConsoleOut)
                    {
                        Console.WriteLine("\r\n\r\n=========================================================");
                        Console.WriteLine("开始执行任务:" + job.Name);
                        Console.WriteLine("\r\n");
                    }


                    // 执行每个任务
                    TaskProcessor task = new TaskProcessor();
                    task.Execute(job, s_enableConsoleOut);
                }
                catch (Exception ex) {
                    ProcessException(ex);
                }
            }
        }
示例#2
0
        /// <summary>
        ///     Missing belief is guessed
        ///     The worker possibly complete the task incorrectly
        ///     and learn by doing
        /// </summary>
        /// <param name="task"></param>
        /// <param name="blocker"></param>
        /// <param name="murphy"></param>
        /// <param name="resolution"></param>
        public void RecoverBlockerIncompleteByGuessing(SymuTask task, Blocker blocker, MurphyIncomplete murphy,
                                                       BlockerResolution resolution)
        {
            if (task is null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            if (murphy == null)
            {
                throw new ArgumentNullException(nameof(murphy));
            }

            var impact = murphy.NextGuess();

            if (impact > task.Incorrectness)
            {
                task.Incorrectness = impact;
            }

            if (task.Incorrectness == ImpactLevel.Blocked)
            {
                //Agent decide to cancel the task
                TaskProcessor.Cancel(task);
            }
            else
            {
                task.Weight *= murphy.NextImpactOnTimeSpent();
                if (blocker != null)
                {
                    task.Recover(blocker, resolution);
                }
            }
        }
示例#3
0
        private void Client_OnValidateGameInfo(HClient arg1, string authString, string hash)
        {
            string str = string.Format("OnValidateGameInfo: AuthToken({0}), Hash({1})", AuthStringManager.AuthStringToAscii(authString), AuthStringManager.AuthStringToAscii(hash));

            LogThread.Log(str, LogInterface.LogMessageType.Normal, true);
            TaskProcessor.AddTask(new HTask(HTask.HTaskType.ValidateGameInfo, arg1, authString, hash));
        }
示例#4
0
        public override void NewAuthorizedClient(GameClient client)
        {
            base.NewAuthorizedClient(client);


            TaskProcessor.AddTask(new HTask(HTask.HTaskType.ValidateGameInfo, (HClient)client, client.AuthString, null));
        }
示例#5
0
        private void Client_OnPuzzleComplete(object sender, PuzzleCompleteArgs e)
        {
            string str = string.Format("OnPuzzleComplete: Tower({0}), Floor({1}), Time({2}), AuthToken({3})", e.TowerIndex, e.FloorNumber, e.CompletionTime, AuthStringManager.AuthStringToAscii(e.AuthToken));

            LogThread.Log(str, LogInterface.LogMessageType.Normal, true);
            TaskProcessor.AddTask(new HTask(HTask.HTaskType.PuzzleComplete_FetchData, (HClient)sender, e));
        }
        public IHttpActionResult UpdateProfile([FromBody] string clientProfile)
        {
            if (string.IsNullOrEmpty(this.User.Identity.Name))
            {
                return(this.Ok());
            }

            dynamic obj        = JsonConvert.DeserializeObject(clientProfile);
            var     clientUser = ProfileHelper.GetClientUser(this.User.Identity.Name);

            clientUser.UserFilter = FilterFromPost(obj.company);
            clientUser.CompetitorFilter.Clear();
            foreach (var item in obj.competitors)
            {
                if (item.name == "" || item.filters.Count == 0)
                {
                    continue;
                }
                var filter = FilterFromPost(item);
                clientUser.CompetitorFilter.Add(filter);
            }
            clientUser.UserFilter.UserName = this.User.Identity.Name;//公司名称不能被修改


            if (this.IsValidFilter(clientUser) || IsValidCompetitorFilter(clientUser))
            {
                ProfileHelper.UpdateClientUser(clientUser);
                clientUser = ProfileHelper.GetClientUser(this.User.Identity.Name);
                BackgroundJob.Enqueue(() => TaskProcessor.InitDataFast(clientUser));
            }

            return(this.Ok(clientUser));
        }
示例#7
0
        private void Client_OnSpendCoins(object sender, SpendCoinsArgs e)
        {
            string str = string.Format("OnSpendCoins: SpendOn({0}), Coins({1}), AuthToken({2})", e.SpendOn, e.Coins, AuthStringManager.AuthStringToAscii(e.AuthToken));

            LogThread.Log(str, LogInterface.LogMessageType.Normal, true);
            TaskProcessor.AddTask(new HTask(HTask.HTaskType.SpendCoins, (HClient)sender, e));
        }
示例#8
0
        static void Main(string[] args)
        {
            Console.WriteLine("------------------------------------------------------------------------");
            Console.WriteLine("Utility to rename, set creation date or delete files");
            Console.WriteLine("------------------------------------------------------------------------");

            try
            {
                var(tasks, options) = ArgParser.Parse(args, new TaskValidator());
                if (tasks is null || options is null)
                {
                    PrintUsage();
                    return;
                }

                var processor = new TaskProcessor(options, new FileProcessorFactory());
                processor.Execute(tasks);
            }
            catch (Exception ex)
            {
                ConsoleLog.WriteError(ex.Message);
            }

            Console.WriteLine();
            Console.WriteLine("------------------------------------------------------------------------");
            Console.WriteLine(">> Done. Press ENTER to quit. ");
            Console.ReadLine();
        }
示例#9
0
 public SingleActor(TaskActor taskActor,
                    TaskProcessor taskProcessor,
                    IImportTrackerRepository importTrackerRepository)
 {
     _taskActor               = taskActor;
     _taskProcessor           = taskProcessor;
     _importTrackerRepository = importTrackerRepository;
 }
示例#10
0
    public void ReplaceProcessor(TaskProcessor newValue)
    {
        var index     = TaskComponentsLookup.Processor;
        var component = CreateComponent <ProcessorComponent>(index);

        component.value = newValue;
        ReplaceComponent(index, component);
    }
示例#11
0
 public void TestMagicHeaderMissing()
 {
     const string text = "Test test test, ho ho ho. ";
     const string compressedTxt = "compressed.txt";
     File.WriteAllText("in.txt", text);
     var parameters = new TaskParameters(ProcessorMode.Decompress, "in.txt", compressedTxt);
     var processor = new TaskProcessor(new LoggerMock());
     Assert.Throws<Exception>(() => processor.Start(parameters).Wait());
 }
示例#12
0
 public RecoveryActor(ImportProcessor importProcessor,
                      BatchProcessor batchProcessor,
                      TaskProcessor taskProcessor,
                      List <TaskActor> taskActors)
 {
     _importProcessor = importProcessor;
     _batchProcessor  = batchProcessor;
     _taskProcessor   = taskProcessor;
     _taskActors      = taskActors;
 }
示例#13
0
        public ActionResult AddTask(TaskModel model)//añade una tarea a la base de datos
        {
            if (ModelState.IsValid)
            {
                int recordsCreated = TaskProcessor.CreateTask(model.TaskName, model.TaskCompleted);
                return(RedirectToAction("ViewTasks"));
            }

            return(View());
        }
示例#14
0
 public BrokerActor(ImportProcessor importProcessor,
                    BrokerTransactionScraper brokerTransactionScraper,
                    BatchProcessor batchProcessor,
                    TaskProcessor taskProcessor,
                    IConfiguration configuration)
 {
     _importProcessor          = importProcessor;
     _brokerTransactionScraper = brokerTransactionScraper;
     _configuration            = configuration;
     _batchProcessor           = batchProcessor;
     _taskProcessor            = taskProcessor;
 }
示例#15
0
        public ActionResult DeleteTasks(TaskModel model)//Borra una tarea de la base de datos
        {
            ViewBag.Message = "Tasks List";

            if (ModelState.IsValid)
            {
                TaskProcessor.DeleteTask(model.TaskName);
                return(RedirectToAction("ViewTasks"));
            }

            return(RedirectToAction("ViewTasks"));
        }
示例#16
0
        /// <summary>
        ///     Starts the agent execution, after it has been created.
        ///     First, the Setup method is called, and then the Act method is automatically called when the agent receives a
        ///     message.
        /// </summary>
        public override void Start()
        {
            base.Start();

            // TaskProcessor initializing
            if (!Cognitive.TasksAndPerformance.CanPerformTask)
            {
                return;
            }

            TaskProcessor = new TaskProcessor(Cognitive.TasksAndPerformance.TasksLimit, Environment.Debug);
            OnAfterTaskProcessorStart();
        }
示例#17
0
        public void TestTaskAbortion()
        {
            var text = string.Concat(Enumerable.Repeat("Test test test, ho ho ho. ", 200500));
            const string compressedTxt = "compressed.txt";
            File.WriteAllText("in.txt", text);
            var parameters = new TaskParameters(ProcessorMode.Compress, "in.txt", compressedTxt);
            var processor = new TaskProcessor(new LoggerMock());
            var task = processor.Start(parameters);

            task.Abort();
            task.Wait();
            Assert.True(task.IsErrorOccured);
        }
示例#18
0
    static void Main(string[] args)
    {
        TaskProcessor tp = new TaskProcessor();

        Thread t1 = new Thread(new ParameterizedThreadStart(tp.SubmitRequest));

        t1.Start(1);
        Thread t2 = new Thread(new ParameterizedThreadStart(tp.SubmitRequest));

        t2.Start(2);
        Thread t3 = new Thread(new ParameterizedThreadStart(tp.SubmitRequest));

        t3.Start(3);
    }
示例#19
0
        public ToDoDashboard()
        {
            InitializeComponent();
            Left = 25;
            Top  = 20;

            addTask1.Left = -addTask1.Width;
            directory     = new AudioDirectories();

            todoProcessor = new TaskProcessor();
            player        = new AudioAlarm();

            alarmTimer          = new System.Timers.Timer(1000);
            alarmTimer.Elapsed += Timer_Elapsed;
        }
示例#20
0
        /// <summary>
        ///     Post a task in the TasksProcessor
        /// </summary>
        /// <param name="task"></param>
        /// <remarks>Don't use TaskProcessor.Post directly to handle the OnBeforeTaskPost event</remarks>
        public void Post(SymuTask task)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            // if filtering tasks here, we must unassigned the task otherwise the task would not be taken by anyone
            // for the moment it is not filtered
            if (!Cognitive.TasksAndPerformance.CanPerformTask) // || task.IsCancelledBy(Id)) //|| task.IsBlocked)
            {
                return;
            }

            OnBeforePostTask(task);
            TaskProcessor.Post(task);
            OnAfterPostTask(task);
        }
示例#21
0
        public ActionResult ViewUnfinishedTasks()//toma las tareas incompletas de la base de datos, las guarda en una lista de objetos tipo TaskModel y muestra la lista en la vista
        {
            ViewBag.Message = "Completed Tasks List";

            var data = TaskProcessor.LoadUnfinishedTask();
            List <TaskModel> tasks = new List <TaskModel>();

            foreach (var row in data)
            {
                tasks.Add(new TaskModel
                {
                    TaskName      = row.TaskName,
                    TaskCompleted = row.TaskCompleted
                });
            }

            return(View(tasks));
        }
示例#22
0
        public void TestErrorOnDecompress()
        {
            const string text = "Test test test, ho ho ho";
            const string compressedTxt = "compressed.gz";
            const string decompressedTxt = "decompressed.txt";
            File.WriteAllText("in.txt", text);
            var parameters = new TaskParameters(ProcessorMode.Compress, "in.txt", compressedTxt);
            var processor = new TaskProcessor(new LoggerMock());
            var task = processor.Start(parameters);
            task.Wait();

            File.AppendAllText(compressedTxt, "a0b4");

            parameters = new TaskParameters(ProcessorMode.Decompress, compressedTxt, decompressedTxt);
            task = processor.Start(parameters);
            task.Wait();

            Assert.True(task.IsErrorOccured);
        }
示例#23
0
        /// <summary>
        ///     Check a particular beliefId from Task.BeliefBits against Agent.Beliefs
        ///     Prevent the agent from acting on a particular belief
        ///     Task may be blocked if it is the case
        /// </summary>
        public void CheckRiskAversion(SymuTask task, IAgentId knowledgeId)
        {
            if (task is null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            if (!BeliefsModel.On)
            {
                return;
            }

            var   taskBits       = task.KnowledgesBits.GetBits(knowledgeId);
            float mandatoryScore = 0;
            byte  mandatoryIndex = 0;

            var belief      = BeliefsModel.GetBeliefFromKnowledgeId(knowledgeId);
            var actorBelief = BeliefsModel.GetActorBelief(knowledgeId);

            MurphyIncompleteBelief.CheckRiskAversion(belief, taskBits, actorBelief, ref mandatoryScore,
                                                     ref mandatoryIndex, -Cognitive.InternalCharacteristics.RiskAversionValue());
            if (!(mandatoryScore <= -Cognitive.InternalCharacteristics.RiskAversionValue()))
            {
                return;
            }

            var murphy = Environment.MainOrganization.Murphies.IncompleteBelief;

            // Prevent the agent from acting on a particular belief
            if (murphy.ShouldGuess((byte)task.HasBeenCancelledBy.Count))
            {
                // to avoid complete blocking, we allow the agent, depending on the Murphies.IncompleteBelief parameters
                // to unblock the task
                var blocker = task.Add(Murphy.IncompleteBelief, Schedule.Step, knowledgeId, mandatoryIndex);
                RecoverBlockerIncompleteBeliefByGuessing(task, blocker);
            }
            else
            {
                // Agent can cancel the task a certain number of times
                TaskProcessor.Cancel(task);
            }
        }
示例#24
0
        public void OverallTest()
        {
            const string text = "Test test test, ho ho ho";
            const string compressedTxt = "compressed.txt";
            const string decompressedTxt = "decompressed.txt";
            File.WriteAllText("in.txt", text);
            var parameters = new TaskParameters(ProcessorMode.Compress, "in.txt", compressedTxt);
            var processor = new TaskProcessor(new LoggerMock());
            var task = processor.Start(parameters);
            task.Wait();

            Assert.True(File.Exists(compressedTxt));
            Assert.NotEqual(Encoding.UTF8.GetBytes(text), File.ReadAllBytes(compressedTxt));

            parameters = new TaskParameters(ProcessorMode.Decompress, compressedTxt, decompressedTxt);
            task = processor.Start(parameters);
            task.Wait();

            Assert.True(File.Exists(decompressedTxt));
            Assert.Equal(text, File.ReadAllText(decompressedTxt));
        }
示例#25
0
        /// <summary>
        ///     Post a task in the TasksProcessor
        /// </summary>
        /// <param name="tasks"></param>
        /// <remarks>Don't use TaskProcessor.Post directly to handle the OnBeforeTaskPost event</remarks>
        public void Post(IEnumerable <SymuTask> tasks)
        {
            if (tasks is null)
            {
                throw new ArgumentNullException(nameof(tasks));
            }

            if (!Cognitive.TasksAndPerformance.CanPerformTask)
            {
                return;
            }

            // if filtering tasks here, we must unassigned the task otherwise the task would not be taken by anyone
            // for the moment it is not filtered
            foreach (var task in tasks) //.Where(x => !x.IsCancelledBy(Id))) //.Where(x => !x.IsBlocked))
            {
                OnBeforePostTask(task);
                TaskProcessor.Post(task);
                OnAfterPostTask(task);
            }
        }
示例#26
0
        public void TestFileWithSeveralChunks()
        {
            var text = string.Concat(Enumerable.Repeat("Test test test, ho ho ho. ", 100500));
            const string compressedTxt = "compressed.txt";
            const string decompressedTxt = "decompressed.txt";
            File.WriteAllText("in.txt", text);
            var parameters = new TaskParameters(ProcessorMode.Compress, "in.txt", compressedTxt);
            var processor = new TaskProcessor(new LoggerMock());
            var task = processor.Start(parameters);
            task.Wait();

            Assert.True(File.Exists(compressedTxt));
            Assert.NotEqual(Encoding.UTF8.GetBytes(text), File.ReadAllBytes(compressedTxt));

            parameters = new TaskParameters(ProcessorMode.Decompress, compressedTxt, decompressedTxt);
            task = processor.Start(parameters);
            task.Wait();

            Assert.True(File.Exists(decompressedTxt));
            Assert.False(task.IsErrorOccured);
            Assert.Equal(text, File.ReadAllText(decompressedTxt));
        }
示例#27
0
    // Start is called before the first frame update
    void Start()
    {
        if (taskProcessor == null)
        {
            taskProcessor = GetComponent <TaskProcessor>();
        }

        currentDropHolder     = null;
        currentDragObject     = null;
        _camera               = Camera.main;
        taskDataSlots         = new List <TaskDataSlot>();
        dragDropHolders       = transform.GetComponentsInChildren <DragDropHolder>();
        taskCalculationHelper = new TaskCalculationHelper();

        TaskPickScrollRect.OnBeginDragEvent += NotifyUILock;
        TaskPickScrollRect.OnEndDragEvent   += NotifyUIRelease;

        taskProcessor.OnTaskDone += Init;

        AssignOnDropEvent(dragDropHolders);

        Init();
    }
示例#28
0
        /// <summary>
        ///     Trigger every event before the new step
        ///     Do not send messages, use NextStep for that
        /// </summary>
        public override async void PreStep()
        {
            MessageProcessor?.ClearMessagesPerPeriod();
            ForgettingModel?.InitializeForgettingProcess();

            // Databases
            if (HasEmail)
            {
                Email.ForgettingProcess(Schedule.Step);
            }

            _newInteractionCounter = 0;

            var isolated = Cognitive.InteractionPatterns.IsIsolated(Schedule.Step);

            HandleStatus(isolated);
            // intentionally after Status
            HandleCapacity(isolated, true);
            // Task manager
            if (!Cognitive.TasksAndPerformance.CanPerformTask)
            {
                return;
            }

            async Task <bool> ProcessWorkInProgress()
            {
                while (Capacity.HasCapacity && Status != AgentStatus.Offline)
                {
                    try
                    {
                        var task = await TaskProcessor.Receive(Schedule.Step).ConfigureAwait(false);

                        switch (task.Parent)
                        {
                        case Message message:
                            // When Schedule.Type is Intraday, messages are treated as tasks and stored in task.Parent attribute
                            // Once a message (as a task) is receive it is treated as a message
                            if (!task.IsStarted)
                            {
                                ActMessage(message);
                            }

                            WorkOnTask(task);
                            break;

                        default:
                            WorkInProgress(task);
                            break;
                        }
                    }
                    catch (Exception exception)
                    {
                        var exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception);
                        exceptionDispatchInfo.Throw();
                    }
                }

                // If we didn't deschedule then run the continuation immediately
                return(true);
            }

            await ProcessWorkInProgress().ConfigureAwait(false);

            if (Schedule.Type <= TimeStepType.Daily)
            {
                ActEndOfDay();
            }
        }
示例#29
0
        [TestMethod] public void TestBaseFunctionality()
        {
            long oneDay  = TimeSpan.FromDays(1.0).Ticks;
            long oneHour = TimeSpan.FromHours(1.0).Ticks;

            Model model = new Model();

            model.AddService <ITaskManagementService>(new TaskManagementService());

            Task[] tasks = new Task[] { new MyTask(model, 0), new DelayTask(model, 1, oneDay), new MyTask(model, 2), new DelayTask(model, 3, oneHour) };

            int[] from = new int[] { 0, 0, 1, 2 }; //,4,5,6,7,8};
            int[] to   = new int[] { 1, 3, 2, 3 }; //,4,6,5,9,1};

            ArrayList childTasks = new ArrayList();

            foreach (Task task in tasks)
            {
                childTasks.Add(task);
            }

            for (int ndx = 0; ndx < to.Length; ndx++)
            {
                Task taskA = (Task)((Edge)childTasks[from[ndx]]);
                Task taskB = (Task)((Edge)childTasks[to[ndx]]);

                Debug.WriteLine(String.Format("Considering a connection between {0} and {1}.", taskA.Name, taskB.Name));

                int forward  = PathLength.ShortestPathLength(taskA, taskB);
                int backward = PathLength.ShortestPathLength(taskB, taskA);

                Debug.WriteLine(String.Format("Forward path length is {0}, and reverse path length is {1}.", forward, backward));

                if ((forward == int.MaxValue) && (backward == int.MaxValue))
                {
                    taskA.AddSuccessor(taskB);
                    Debug.WriteLine(String.Format("{0} will follow {1}.", taskB.Name, taskA.Name));
                }
                else if ((forward != int.MaxValue) && (backward == int.MaxValue))
                {
                    taskA.AddSuccessor(taskB);
                    Debug.WriteLine(String.Format("{0} will follow {1}.", taskB.Name, taskA.Name));
                }
                else if ((forward == int.MaxValue) && (backward != int.MaxValue))
                {
                    taskB.AddSuccessor(taskA);
                    Debug.WriteLine(String.Format("{1} will follow {0}.", taskB.Name, taskA.Name));
                }
                else
                {
                    throw new ApplicationException("Cycle exists between " + taskA.Name + " and " + taskB.Name + ".");
                }
            }

            Task topTask = new Task(model, "Parent", Guid.NewGuid());

            topTask.AddChildEdges(childTasks);
            TaskProcessor tp = new TaskProcessor(model, "Task Processor", topTask);

            tp.SetStartTime(DateTime.Now);
            model.GetService <ITaskManagementService>().AddTaskProcessor(tp);

            model.StateMachine.InboundTransitionHandler(model.GetStartEnum()).Commit += new CommitTransitionEvent(OnModelStarting);

            model.Start();
            if (model.StateMachine.State.Equals(StateMachine.GenericStates.Running))
            {
                Debug.WriteLine("Error attempting to transition to Started state.");
            }
        }
示例#30
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     TaskProcessor?.Dispose();
 }