Beispiel #1
0
        private void LogToDataBase(JobMessage message)
        {
            string conectionString = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;

            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString);

            connection.Open();

            int messageType;

            if (message.IsAMessage())
            {
                messageType = 1;
            }
            else if (message.IsAnError())
            {
                messageType = 2;
            }
            else
            {
                messageType = 3;
            }

            string query = "INSERT INTO LOG VALUES('" + message.getMessage() + "', " + messageType.ToString() + ")";

            SqlCommand command = new SqlCommand(query, connection);

            command.ExecuteNonQuery();
        }
Beispiel #2
0
        public void LogMessage(JobMessage message)
        {
            if (message.getMessage().Length == 0)
            {
                return;
            }

            if (!(message.IsAnError() && _logError) && !(message.IsAWarning() && _logWarning) && !(message.IsAMessage() && _logMessage))
            {
                return;
            }

            if (_logToDatabase)
            {
                LogToDataBase(message);
            }

            if (_logToFile)
            {
                LogToFile(message);
            }

            if (_logToConsole)
            {
                LogToConsole(message);
            }
        }
Beispiel #3
0
        public async Task <ReturnT> Execute(JobMessage job)
        {
            var handler = await _handlerProvider.GetInstanceAsync(job.ExecutorHandler);

            if (handler == null)
            {
                return(ReturnT.Failed($"没有找到名为{job.ExecutorHandler}的JobHandler"));
            }

            // if killed
            if (job.Status == JobStatus.Killed)
            {
                return(ReturnT.Failed($"任务已被终止,id:{job.Id}, reason: {job.Reason}, logId: {job.LogId}"));
            }

            job.Run();

            try
            {
                return(await handler.Execute(new JobExecuteContext(job.Id, job.ExecutorParams)));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "xxljob执行任务错误");
                return(ReturnT.Failed(e.Message));
            }
        }
        public async Task ConsumeReadyJob()
        {
            var jobPool = new JobPool <T>();

            var readyQueue = new ReadyQueue <T>();

            while (true)
            {
                try
                {
                    var job = await readyQueue.GetJobFromReadyQueue(typeof(T).Name, 3);

                    if (job == null)
                    {
                        await Task.Delay(500);

                        continue;
                    }

                    await jobPool.DelJobAsync(job.JobId);

                    var message = new JobMessage <T>(job);
                    using var scope = _serviceProvider.CreateScope();
                    var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();
                    await mediator.Send(message);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, $"ConsumeReadyJob Error; Topic:{typeof(T).Name}");

                    await Task.Delay(1000);
                }
            }
        }
Beispiel #5
0
 public static Job MessageToJob(JobMessage jm)
 {
     return(new Job
     {
         JobID = jm.Id,
         Title = jm.Title,
     });
 }
        public Task <bool> Handle(JobMessage <TestJob> request, CancellationToken cancellationToken)
        {
            var data = request.Data;

            _logger.LogInformation("TestJobHandler消费;Topic:{Topic},JobId:{JobId},Body:{Body}", request.Topic,
                                   data.JobId, data.Body);

            DelayedRedisHelper.RPush(nameof(TestJobHandler), data.JobId);
            return(Task.FromResult(true));
        }
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("__________Let's check_______________");

            var mesage = new JobMessage()
            {
                Message = "Let's check"
            };

            await _publisher.PublishJobMessage(mesage);
        }
Beispiel #8
0
        public Task <bool> Handle(JobMessage <TestJob> request, CancellationToken cancellationToken)
        {
            var data = request.Data;

            _logger.LogInformation(
                $"TestJobHandler消费;Topic:{{Topic}},JobId:{{JobId}},Body:{{Body}}," +
                $"time:{DateTime.Now:yyyy-MM-dd HH:mm:ss}", request.Topic,
                data.JobId, data.Body);

            return(Task.FromResult(true));
        }
Beispiel #9
0
        public override Task <Empty> UpdateJob(JobMessage request, ServerCallContext context)
        {
            Job j = ConversionStuff.MessageToJob(request);

            if (!ValidationUtility.IsJobValid(j))
            {
                return(Task.FromResult(new Empty()));
            }
            unitOfWork.JobRepo.Update(j);
            unitOfWork.Save();
            return(Task.FromResult(new Empty()));
        }
Beispiel #10
0
        private void LogToFile(JobMessage message)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
            string fileMessage = String.Empty;

            if (File.Exists(ConfigurationManager.AppSettings["LogFileDirectory"] + DateTime.Now.ToShortDateString() + ".txt"))
            {
                fileMessage = File.ReadAllText(ConfigurationManager.AppSettings["LogFileDirectory"] + DateTime.Now.ToShortDateString() + ".txt");
            }

            fileMessage = fileMessage + DateTime.Now.ToLongTimeString() + " : " + message.getMessage() + "\n";

            File.WriteAllText(ConfigurationManager.AppSettings["LogFileDirectory"] + DateTime.Now.ToShortDateString() + ".txt", fileMessage);
        }
        public async Task Post([FromBody] JobMessage job)
        {
            if (job == null || string.IsNullOrWhiteSpace(job.JobDescription))
            {
                throw new Exception($"Value for {nameof(job)} is missing.");
            }

            if (string.IsNullOrWhiteSpace(_connectionStringForWriting))
            {
                throw new ConfigurationErrorsException($"Provide an AppSetting or Environment Variable named '{MicrosoftServicebusConnectionStringSettingName}' that holds a connection string that has write access to your Azure Service Bus.");
            }

            await SendMessageAsync(job.JobDescription);
        }
Beispiel #12
0
        public Task Enqueue(JobMessage job)
        {
            lock (_jobs)
            {
                _jobs.Enqueue(job);
                if (!_delegateQueuedOrRunning)
                {
                    _delegateQueuedOrRunning = true;
                    ThreadPool.UnsafeQueueUserWorkItem(ProcessQueuedItems, null);
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #13
0
        private static ServerMessage _ConvertJobMessage(JobMessage msg)
        {
            Debug.Assert(msg != null);

            var type = ServerMessageType.Info;

            if (msg.Type == NAJobMessageType.esriJobMessageTypeError)
            {
                type = ServerMessageType.Error;
            }
            else if (msg.Type == NAJobMessageType.esriJobMessageTypeWarning)
            {
                type = ServerMessageType.Warning;
            }

            return(new ServerMessage(type, msg.Description));
        }
Beispiel #14
0
        private void LogToConsole(JobMessage message)
        {
            if (message.IsAnError())
            {
                Console.ForegroundColor = ConsoleColor.Red;
            }
            else if (message.IsAWarning())
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
            }
            else if (message.IsAMessage())
            {
                Console.ForegroundColor = ConsoleColor.White;
            }

            Console.WriteLine(DateTime.Now.ToShortDateString() + " | " + DateTime.Now.ToLongTimeString() + " : " + message.getMessage());
        }
Beispiel #15
0
        public async Task Handle(JobMessage message)
        {
            if (IsNew && !string.IsNullOrWhiteSpace(Data.JobId))
            {
                _events.Enqueue("The JobId property of my saga data was set as expected");
            }
            else if (IsNew)
            {
                _events.Enqueue("The JobId property of my saga data was NOT set as expected");
            }
            else
            {
                _events.Enqueue("The JobId property of my saga data was NOT set as expected");
            }

            _counter.Decrement();
        }
Beispiel #16
0
        public async Task UpdateJob(JobMessage jobMessage)
        {
            if (client == null || token == "")
            {
                Debug.WriteLine("Null client or token");
                return;
            }

            try
            {
                await client.UpdateJobAsync(jobMessage, headers);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
        public override void Run()
        {
            var baseKey = new JobMessage()
            {
                Category = "01", Name = this.Name, BaseKey = Guid.NewGuid()
            };

            //the time at which the job will run
            var currentBaseTimePoint = DateTime.Now.Date.Add(startSpan);

            var baseDate = DateTime.Now <= currentBaseTimePoint?currentBaseTimePoint.AddDays(-1) : currentBaseTimePoint;

            while (_running)
            {
                var nextDay = baseDate.AddDays(1);
                //current data is greater than baseDate if the job is running slowly
                while (nextDay < DateTime.Now)
                {
                    baseDate = nextDay;
                    nextDay  = nextDay.AddDays(1);
                }
                var baseTime = nextDay - baseDate;

                if (!TimePending.Pending(baseTime, baseDate, baseKey))
                {
                    if (UnitContainer != null && _running)
                    {
                        //Store the info of timer
                        if (!this.Parameters.AllKeys.Contains(JobDictionary.JOB_INTERNAL_TIMER_PATTERN))
                        {
                            this.Parameters.Add(JobDictionary.JOB_INTERNAL_TIMER_PATTERN, null);
                        }
                        if (!this.Parameters.AllKeys.Contains(JobDictionary.JOB_INTERNAL_TIMER_TIME))
                        {
                            this.Parameters.Add(JobDictionary.JOB_INTERNAL_TIMER_TIME, Parameters["jobTime"]);
                        }

                        UnitContainer.InvokeALL(this.Parameters);
                    }
                    baseDate = nextDay;
                    GC.Collect();
                    GC.WaitForFullGCComplete();
                }
            }
        }
Beispiel #18
0
        public void LoggerJob()
        {
            string sql    = "";
            DbHelp dbHelp = new DbHelp(ConnString);

            #region 更新任务时间
            sql = string.Format("UPDATE [dbo].[sys_job] SET lastFireTime = '{0}', nextFireTime = '{1}' WHERE jobName = '{2}';", LastFireTime, NextFireTime, JobName);
            dbHelp.DataOperator(sql);
            #endregion

            #region 记录任务日志
            stopwatch.Stop();
            JobMessage = "总共耗时:" + stopwatch.Elapsed.TotalMilliseconds.ToString() + " 毫秒";

            JobName       = JobName.Replace("'", "''");
            JobGroup      = JobGroup.Replace("'", "''");
            MethodName    = MethodName.Replace("'", "''");
            MethodParams  = MethodParams.Replace("'", "''");
            JobMessage    = JobMessage.Replace("'", "''");
            ExceptionInfo = ExceptionInfo.Replace("'", "''");

            sql = string.Format(@"INSERT INTO [dbo].[sys_job_log]
                        ([jobName]
                        ,[jobGroup]
                        ,[methodName]
                        ,[methodParams]
                        ,[jobMessage]
                        ,[exceptionInfo]
                        ,[createTime]
                        ,[createBy])
                    VALUES
                        ('{0}'
                        ,'{1}'
                        ,'{2}'
                        ,'{3}'
                        ,'{4}'
                        ,'{5}'
                        , GETDATE()
                        , 'System')", JobName, JobGroup, MethodName, MethodParams, JobMessage, ExceptionInfo);
            dbHelp.DataOperator(sql);
            #endregion
        }
Beispiel #19
0
        public async Task CheckReservation(JobMessage message)
        {
            _logger.LogInformation("start check");
            var awaitMessage = "Let's check";

            if (message.Message == awaitMessage)
            {
                var allReservation = _reservation.Find(_ => true).ToList();

                foreach (var finishDates in allReservation)
                {
                    if (DateTime.UtcNow > finishDates.FinishDateOfBooking)
                    {
                        var id = finishDates.Id;
                        _reservation.DeleteOne(Builders <Reservation> .Filter.Eq("Id", id));
                    }
                }
            }
            _logger.LogInformation("finish check");
        }
Beispiel #20
0
        public override void Run()
        {
            if (DebugContainer.Debuggers == null || UnitContainer.Units == null)
            {
                throw new Exception("JobManager have not been initialized");
            }

            //UnitContainer.InvokeALL();

            if (t != null)
            {
                t.Start();

                _baseKey = new JobMessage()
                {
                    Category = "02", Name = this.Name, BaseKey = Guid.NewGuid()
                };

                //LogInfor.GetLogger<TimerLogger>().WriteInfo(_baseKey.Format() + " - Left time[" + (t.Interval/100).ToString() + "s]", "", "");
            }
        }
Beispiel #21
0
        public async Task <IActionResult> Post([FromBody] JobMessage value)
        {
            using (_db)
            {
                _logger.LogDebug("Inserting job:{1} for user:{0}", User, $"{value.Registered}");

                var job = new Job
                {
                    CarId        = value.CarId,
                    Description  = value.Description,
                    AssignedToId = value.AssignedToId
                };

                await _db.Jobs.AddAsync(job);

                await _db.SaveChangesAsync();

                await _db.Entry(job).Reference(j => j.Car).LoadAsync();

                await _db.Entry(job).Reference(j => j.AssignedTo).LoadAsync();

                return(Ok(job));
            }
        }
        public async Task <IActionResult> Post([FromBody] JobMessage job)
        {
            if (string.IsNullOrWhiteSpace(_connectionStringForWriting))
            {
                string error = $"Provide an Environment Variable named '{MicrosoftServicebusConnectionStringSettingName}' that holds a connection string that has write access to your Azure Service Bus.";
                await LogMessageAsync($"Bad request received: '{error}'");

                return(BadRequest(error));
            }

            if (string.IsNullOrWhiteSpace(job.JobDescription))
            {
                var error = $"A value for '{job.JobDescription}' is required.";
                await LogMessageAsync($"Bad request received: '{error}'");

                return(BadRequest(error));
            }

            await LogMessageAsync($"Enqueueing job: {job.JobDescription}");

            await EnqueueJobAsync(job.JobDescription);

            return(Accepted());
        }
Beispiel #23
0
 /// <summary>
 /// 添加任务
 /// </summary>
 /// <param name="jobInfo"></param>
 /// <returns></returns>
 public async Task Enqueue(JobMessage job)
 {
     await _publishedChannel.Writer.WriteAsync(job);
 }
        public override void Run()
        {
            if (DebugContainer.Debuggers == null || UnitContainer.Units == null)
            {
                throw new Exception("JobManager have not been initialized");
            }

            DateTime baseDate = new DateTime();

            if (JobTimeFormatter != null)
            {
                baseDate = JobTimeFormatter.FormatTime;
            }

            JobMessage baseKey = new JobMessage()
            {
                Category = "00", Name = this.Name, BaseKey = Guid.NewGuid()
            };

            while (_running)
            {
                try
                {
                    //By specified time
                    if (JobTimeFormatter != null)
                    {
                        TimeSpan baseTime = new TimeSpan();
                        switch (JobTimeFormatter.Type)
                        {
                        case JobDictionary.JobTimeType.M:
                            var nextYear = baseDate.AddYears(1);
                            //current data is greater than baseDate if the job is running slowly
                            while (nextYear < DateTime.Now)
                            {
                                baseDate = nextYear;
                                nextYear = nextYear.AddYears(1);
                            }
                            baseTime = nextYear - baseDate;
                            if (!TimePending.Pending(baseTime, baseDate, baseKey))
                            {
                                _run();
                                //Prepare for the next plan
                                baseDate = nextYear;
                            }
                            break;

                        case JobDictionary.JobTimeType.D:
                            var nextMonth = baseDate.AddMonths(1);
                            //current data is greater than baseDate if the job is running slowly
                            while (nextMonth < DateTime.Now)
                            {
                                baseDate  = nextMonth;
                                nextMonth = nextMonth.AddMonths(1);
                            }
                            baseTime = nextMonth - baseDate;
                            if (!TimePending.Pending(baseTime, baseDate, baseKey))
                            {
                                _run();
                                baseDate = nextMonth;
                            }
                            break;

                        case JobDictionary.JobTimeType.h:
                            var nexDay = baseDate.AddDays(1);
                            //current data is greater than baseDate if the job is running slowly
                            while (nexDay < DateTime.Now)
                            {
                                baseDate = nexDay;
                                nexDay   = nexDay.AddDays(1);
                            }
                            baseTime = nexDay - baseDate;
                            if (!TimePending.Pending(baseTime, baseDate, baseKey))
                            {
                                _run();
                                baseDate = nexDay;
                            }
                            break;

                        case JobDictionary.JobTimeType.m:
                            var nextHour = baseDate.AddHours(1);
                            //current data is greater than baseDate if the job is running slowly
                            while (nextHour < DateTime.Now)
                            {
                                baseDate = nextHour;
                                nextHour = nextHour.AddHours(1);
                            }
                            baseTime = nextHour - baseDate;
                            if (!TimePending.Pending(baseTime, baseDate, baseKey))
                            {
                                _run();
                                baseDate = nextHour;
                            }
                            break;

                        case JobDictionary.JobTimeType.s:
                            var nextMinute = baseDate.AddMinutes(1);
                            //current data is greater than baseDate if the job is running slowly
                            while (nextMinute < DateTime.Now)
                            {
                                baseDate   = nextMinute;
                                nextMinute = nextMinute.AddMinutes(1);
                            }
                            baseTime = nextMinute - baseDate;
                            if (!TimePending.Pending(baseTime, baseDate, baseKey))
                            {
                                _run();
                                baseDate = nextMinute;
                            }
                            break;
                        }
                    }
                }
                catch
                {
                }
            }
        }