示例#1
0
        public (IList <object>, IList <object>) Execute(RecipientState state, AbstractTrigger message)
        {
            var        messagesResult = new List <object>();
            BigInteger amount         = message.Amount;
            int        count          = state.Recipients.Count;

            if (count == 0)
            {
                throw new Exception();
            }
            double weightsSum = 0;

            foreach (TokenPairKey <double> recipient in state.Recipients)
            {
                weightsSum += recipient.GetTag();
            }


            BigInteger portion = amount / (int)weightsSum;

            // We are going to lose tokens because we are using integer
            foreach (TokenPairKey <double> recipient in state.Recipients)
            {
                //msg.To.ChangeAgentId(state.SelfId)
                var command = new TransferTokenMessage(portion, new SingleAngentTokenKey(state.SelfId), recipient);
                amount -= portion;
                messagesResult.Add(command);
            }
            return(messagesResult, null);
        }
示例#2
0
 /// <summary>
 /// 获取任务
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public static TaskOptions GetTaskOptions(this IJobExecutionContext context)
 {
     var _taskList = TaskRepository.GetTaskList();
     AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
     TaskOptions taskOptions = _taskList.Where(x => x.name == trigger.Name && x.group_name == trigger.Group).FirstOrDefault();
     return taskOptions ?? _taskList.Where(x => x.name == trigger.JobName && x.group_name == trigger.JobGroup).FirstOrDefault();
 }
示例#3
0
    public override bool Percept(AbstractTrigger trigger)
    {
        if (trigger.triggerType != TriggerType.Sight)
        {
            return(false);
        }

        var tempTrigger = trigger as SightTrigger;
        //距离
        var  toTarget = tempTrigger.transform.position - transform.position;
        bool result   = toTarget.magnitude < sightDistance;

        //[视角]
        if (enableAngle)
        {
            result = result && Vector3.Angle(transform.forward, toTarget) < sightAngle / 2;
        }
        //[无遮挡]
        if (enableRay)
        {
            RaycastHit hitInfo;
            var        dir = tempTrigger.recivePos.position - sendPos.position;
            result = result &&
                     Physics.Raycast(sendPos.position, dir, out hitInfo, sightDistance) &&
                     hitInfo.collider.gameObject == tempTrigger.gameObject;
        }
        return(result);
    }
示例#4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>通过作业上下文获取作业对应的配置参数
        /// <returns></returns>
        public static TaskOptions GetTaskOptions(this IJobExecutionContext context)
        {
            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            TaskOptions     taskOptions = _taskList.Where(x => x.TaskName == trigger.Name && x.GroupName == trigger.Group).FirstOrDefault();

            return(taskOptions ?? _taskList.Where(x => x.TaskName == trigger.JobName && x.GroupName == trigger.JobGroup).FirstOrDefault());
        }
示例#5
0
 public void Add(AbstractTrigger trigger)
 {
     FactoryForms.FactoryTriggerControl listview = new FactoryForms.FactoryTriggerControl();
     listview.Text  = trigger.GetActionName();
     listview.Value = trigger;
     listBox1.Items.Add(listview);
 }
示例#6
0
 /// <summary>
 /// Gets the misfire instruction text.
 /// </summary>
 /// <param name="trigger">The trigger.</param>
 /// <returns></returns>
 private static string GetMisfireInstructionText(AbstractTrigger trigger)
 {
     if (trigger is CronTriggerImpl)
     {
         return(GetCronTriggerMisfireInstructionText(trigger.MisfireInstruction));
     }
     return(GetSimpleTriggerMisfireInstructionText(trigger.MisfireInstruction));
 }
示例#7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context">通过作业上下文获取作业对应的配置参数</param>
        /// <returns></returns>
        public async Task <ScheduleEntity> GetTaskOptionsAsync(IJobExecutionContext context)
        {
            var _taskList = await _schedulerService.GetAllScheduleNotIsDrop();

            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            ScheduleEntity  taskOptions = _taskList.Where(x => x.Id.ToString() == trigger.Name && x.JobGroupName == trigger.Group).FirstOrDefault();

            return(taskOptions ?? _taskList.Where(x => x.Name == trigger.JobName && x.JobGroupName == trigger.JobGroup).FirstOrDefault());
        }
示例#8
0
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                IQuartzOptionRepository quartzOptionRepository = ServiceLocator.Get <IQuartzOptionRepository>();
                IHttpClientFactory      httpClientFactory      = ServiceLocator.Get <IHttpClientFactory>();
                AbstractTrigger         trigger      = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
                QuartzOption            quartzOption = quartzOptionRepository.SelectSingle(s => (s.JobName == trigger.Name && s.GroupName == trigger.Group) ||
                                                                                           (s.JobName == trigger.JobName && s.GroupName == trigger.JobGroup));
                if (quartzOption == null)
                {
                    throw new ArgumentException(string.Format("分组:{0},作业:{1}不存在", quartzOption.GroupName, quartzOption.JobName));
                }
                HttpClient          httpClient      = httpClientFactory.CreateClient();
                HttpResponseMessage responseMessage = null;
                switch (quartzOption.RequestType)
                {
                case "GET":
                    responseMessage = await httpClient.GetAsync(quartzOption.Api);

                    responseMessage.EnsureSuccessStatusCode();
                    break;

                case "POST":
                    string[] arr = quartzOption.ParameterValue.Split(',');
                    Dictionary <string, string> para = new Dictionary <string, string>();
                    foreach (var item in arr)
                    {
                        string[] itemArr = item.Split(':');
                        para.Add(itemArr[0], itemArr[2]);
                    }
                    FormUrlEncodedContent content = new FormUrlEncodedContent(para);
                    responseMessage = await httpClient.PostAsync(quartzOption.Api, content);

                    responseMessage.EnsureSuccessStatusCode();
                    break;

                case "DELETE":
                    responseMessage = await httpClient.DeleteAsync(quartzOption.Api);

                    responseMessage.EnsureSuccessStatusCode();
                    break;
                }
                ApiResult apiResult = JsonConvert.DeserializeObject <ApiResult>(await responseMessage.Content.ReadAsStringAsync());
                if (apiResult.Code != HttpStatusCode.SUCCESS)
                {
                    throw new HttpRequestException(apiResult.Msg);
                }
                quartzOption.LastActionTime = DateTime.Now;
                quartzOptionRepository.Update(quartzOption);
            }
            catch (Exception ex)
            {
                LogUtils.LogError(ex, "Blog.Quartz.Application.Quartz.Job", ex.Message);
            }
        }
示例#9
0
        public void TriggersShouldBeSerializableSoThatKeyIsSerialized()
        {
            trigger.Key    = new TriggerKey("tname", "tgroup");
            trigger.JobKey = new JobKey("jname", "jgroup");

            AbstractTrigger cloned = trigger.DeepClone();

            Assert.That(cloned.Name, Is.EqualTo(trigger.Name));
            Assert.That(cloned.Group, Is.EqualTo(trigger.Group));
            Assert.That(cloned.Key, Is.EqualTo(trigger.Key));
        }
 public (IList <object>, IList <object>) Execute(RecipientState _, AbstractTrigger message)
 {
     if (message is TokensBurnedTriggerer msg)
     {
         var command = new MintTokenMessage(msg.Amount, msg.From);
         return(new List <object>()
         {
             command
         }, null);
     }
     return(null, null);
 }
示例#11
0
        public Task Execute(IJobExecutionContext context)
        {
            DateTime        dateTime    = DateTime.Now;
            TaskOptions     taskOptions = context.GetTaskOptions();
            string          httpMessage = "";
            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;

            if (taskOptions == null)
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", "未到找作业或可能被移除", true);
                return(Task.CompletedTask);
            }

            if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", "未配置url", true);
                return(Task.CompletedTask);
            }

            try
            {
                Dictionary <string, string> header = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(taskOptions.AuthKey) &&
                    !string.IsNullOrEmpty(taskOptions.AuthValue))
                {
                    header.Add(taskOptions.AuthKey.Trim(), taskOptions.AuthValue.Trim());
                }

                if (taskOptions.RequestType?.ToLower() == "get")
                {
                    httpMessage = HttpManager.HttpGetAsync(taskOptions.ApiUrl, header).Result;
                }
                else
                {
                    httpMessage = HttpManager.HttpPostAsync(taskOptions.ApiUrl, null, null, 60, header).Result;
                }
            }
            catch (Exception ex)
            {
                httpMessage = ex.Message;
            }

            try
            {
                string logContent = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}_{dateTime.ToString("yyyy-MM-dd HH:mm:ss")}_{(string.IsNullOrEmpty(httpMessage)? "OK" : httpMessage)}\r\n";
                FileHelper.WriteFile(FileQuartz.LogPath + taskOptions.GroupName + "\\", $"{taskOptions.TaskName}.txt", logContent, true);
            }
            catch (Exception)
            {
            }
            Console.Out.WriteLineAsync(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + httpMessage);
            return(Task.CompletedTask);
        }
		private void addCommonTriggerData(XNamespace ns, XElement rootTriggerElement, AbstractTrigger trigger)
		{
			rootTriggerElement.Add(
				new XElement(ns + "name", trigger.Key.Name)
				, new XElement(ns + "group", trigger.Key.Group)
				, new XElement(ns + "description", trigger.Description)
				, new XElement(ns + "misfire-instruction", getMisfireInstructionText(trigger))
				//, new XElement(ns + "volatile", trigger.Volatile)
				, new XElement(ns + "job-name", trigger.JobName)
				, new XElement(ns + "job-group", trigger.JobGroup)
				);
		}
示例#13
0
 protected void FillTrigger(AbstractTrigger trigger)
 {
     trigger.Key                = new TriggerKey(Id.Name, Id.Group);
     trigger.JobKey             = JobKey;
     trigger.CalendarName       = CalendarName;
     trigger.Description        = Description;
     trigger.JobDataMap         = JobDataMap;
     trigger.MisfireInstruction = MisfireInstruction;
     trigger.EndTimeUtc         = EndTime;
     trigger.StartTimeUtc       = StartTime;
     trigger.Priority           = Priority;
     trigger.SetNextFireTimeUtc(NextFireTime);
     trigger.SetPreviousFireTimeUtc(PreviousFireTime);
 }
        public async Task Execute(IJobExecutionContext context)
        {
            DateTime        dateTime    = DateTime.Now;
            TaskOptions     taskOptions = context.GetTaskOptions();
            string          httpMessage = "";
            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;

            if (taskOptions == null)
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", "未到找作业或可能被移除", true);
                return;
            }
            Console.WriteLine($"作业[{taskOptions.TaskName}]开始:{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}");
            if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", $"{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}未配置url,", true);
                return;
            }

            try
            {
                Dictionary <string, string> header = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(taskOptions.AuthKey) &&
                    !string.IsNullOrEmpty(taskOptions.AuthValue))
                {
                    header.Add(taskOptions.AuthKey.Trim(), taskOptions.AuthValue.Trim());
                }

                httpMessage = await httpClientFactory.HttpSendAsync(
                    taskOptions.RequestType?.ToLower() == "get"?HttpMethod.Get : HttpMethod.Post,
                    taskOptions.ApiUrl,
                    header);
            }
            catch (Exception ex)
            {
                httpMessage = ex.Message;
            }

            try
            {
                string logContent = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}_{dateTime.ToString("yyyy-MM-dd HH:mm:ss")}_{(string.IsNullOrEmpty(httpMessage) ? "OK" : httpMessage)}\r\n";
                FileHelper.WriteFile(FileQuartz.LogPath + taskOptions.GroupName + "\\", $"{taskOptions.TaskName}.txt", logContent, true);
            }
            catch (Exception)
            {
            }
            Console.WriteLine(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + httpMessage);
            return;
        }
示例#15
0
 protected void FillTrigger(AbstractTrigger trigger)
 {
     trigger.Key                = GetTriggerKey();
     trigger.JobKey             = GetJobKey();
     trigger.CalendarName       = CalendarName;
     trigger.Description        = Description;
     trigger.JobDataMap         = JobDataMap;
     trigger.MisfireInstruction = MisfireInstruction;
     trigger.EndTimeUtc         = null; // Avoid <> checks
     trigger.StartTimeUtc       = StartTime;
     trigger.EndTimeUtc         = EndTime;
     trigger.Priority           = Priority;
     trigger.SetNextFireTimeUtc(NextFireTime?.ToUniversalTime());
     trigger.SetPreviousFireTimeUtc(PreviousFireTime?.ToUniversalTime());
 }
示例#16
0
 public (IList <object>, IList <object>) Execute(RecipientState state, AbstractTrigger message)
 {
     //here To is slef
     if (message is TokensTransferedNotification msg)
     {
         var command     = new BurnTokenMessage(msg.Amount, msg.To);
         var publication = new TokensBurnedTriggerer(state.SelfId, msg.Amount, msg.To);
         return(new List <object>()
         {
             command
         }, new List <object>()
         {
             publication
         });
     }
     return(null, null);
 }
示例#17
0
        public (IList <object>, IList <object>) Execute(RecipientState state, AbstractTrigger message)
        {
            if (message is MockMessageTrigger msg)
            {
                var command = new MintTokenMessage(msg.Amount, msg.To.ChangeAgentId(state.SelfId));

                var publication = new TokensMintedTriggerer(state.SelfId, msg.Amount, msg.To);

                return(new List <object>()
                {
                    command
                }, new List <object>()
                {
                    publication
                });
            }
            return(null, null);
        }
示例#18
0
        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            if (_type == 0)
            {
                AbstractTrigger selected = abstracktrigger_list.Where(e => e.GetActionName() == comboBox.Text).FirstOrDefault();
                global_panelControl = selected.OnSelect();
            }
            if (_type == 1)
            {
                AbstractAction selected = abstrackaction_list.Where(e => e.GetActionName() == comboBox.Text).FirstOrDefault();
                global_panelControl = selected.OnSelect();
            }



            panel1.Controls.Add(global_panelControl);

            //    panel1.Controls.Add(global_trigger.getControl);
        }
示例#19
0
        public (IList <object>, IList <object>) Execute(RecipientState state, AbstractTrigger message)
        {
            var messagesResult    = new List <object>();
            var publicationResult = new List <object>();

            if (state is TokenBurnerState burnerState)
            {
                BigInteger amount = message.Amount;
                while (amount > 0)
                {
                    IAgentTokenKey        recipient = state.Recipients.First();
                    TokensMintedTriggerer element   = burnerState.MintedMessages.FirstOrDefault(x => x.To.Equals(recipient));
                    BigInteger            debt      = element.Amount;
                    IAgentTokenKey        sender    = element.To;

                    BurnTokenMessage      command;
                    TokensBurnedTriggerer command2;

                    if (debt <= amount)
                    {
                        state.Recipients.Remove(recipient);
                        burnerState.MintedMessages.Remove(element);
                        amount  -= debt;
                        command  = new BurnTokenMessage(debt, sender);
                        command2 = new TokensBurnedTriggerer(state.SelfId, debt, recipient);
                    }
                    else
                    {
                        element.Amount -= amount;
                        command         = new BurnTokenMessage(amount, sender);
                        command2        = new TokensBurnedTriggerer(state.SelfId, amount, recipient);

                        amount = 0;
                    }

                    messagesResult.Add(command);
                    publicationResult.Add(command2);
                }
            }
            return(messagesResult, publicationResult);
        }
示例#20
0
        public async override Task Execute(IJobExecutionContext context)
        {
            AbstractTrigger trigger     = context.Trigger as AbstractTrigger;
            TaskOptions     taskOptions = await _taskService.GetTaskByName(trigger.Group, trigger.Name);

            if (taskOptions == null)
            {
                _ = _taskLogService.WriteLog(new TaskLog(taskOptions.Id, TaskLogStatusEnum.Fail, $"{trigger.Group}--{trigger.Name}未到找作业或可能被移除"));
                return;
            }

            if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
            {
                _ = _taskLogService.WriteLog(new TaskLog(taskOptions.Id, TaskLogStatusEnum.Fail, $"{trigger.Group}--{trigger.Name}未配置url"));
            }

            await GetPolicy().ExecuteAsync(ct => ExecuteHttp(taskOptions), new Dictionary <string, object>()
            {
                { "taskId", taskOptions.Id }
            });
        }
示例#21
0
        public async System.Threading.Tasks.Task Execute(IJobExecutionContext context)
        {
            //this.logger.LogWarning($"Hello from scheduled task {DateTime.Now.ToLongTimeString()}");
            //await Task.CompletedTask;

            ScheduleEntity taskOptions = await GetTaskOptionsAsync(context);

            AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;


            if (taskOptions == null)
            {
                //"未到找作业或可能被移除"
                await System.Threading.Tasks.Task.CompletedTask;
            }
            if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
            {
                //"未配置url"
                await System.Threading.Tasks.Task.CompletedTask;
            }
            Dictionary <string, string> header = new Dictionary <string, string>();

            //if (!string.IsNullOrEmpty(sysScheduleModel.AuthKey)
            //    && !string.IsNullOrEmpty(sysScheduleModel.AuthValue))
            //{
            //    header.Add(sysScheduleModel.AuthKey.Trim(), taskOptions.AuthValue.Trim());
            //}

            if (taskOptions.MethodType?.ToUpper() == "GET")
            {
                await HttpUtil.HttpGetAsync(taskOptions.ApiUrl, header);
            }
            else
            {
                await HttpUtil.HttpPostAsync(taskOptions.ApiUrl, null, null, 30000, header);
            }
        }
        public (IList <object>, IList <object>) Execute(RecipientState state, AbstractTrigger message)
        {
            var messagesResult = new List <object>();

            if (message is TokensTransferedNotification msg && msg.To.GetAgentId().Equals(state.SelfId))
            {
                BigInteger amount = message.Amount;
                int        count  = state.Recipients.Count;
                if (count == 0)
                {
                    throw new Exception();
                }
                BigInteger portion = amount / count;
                // We are going to lose tokens because we are using integer
                foreach (IAgentTokenKey recipient in state.Recipients)
                {
                    //msg.To.ChangeAgentId(state.SelfId)
                    var command = new TransferTokenMessage(portion, new SingleAngentTokenKey(state.SelfId), recipient);
                    amount -= portion;
                    messagesResult.Add(command);
                }
            }
            return(messagesResult, null);
        }
示例#23
0
        public async Task Execute(IJobExecutionContext context)
        {
            var sw = new Stopwatch();

            sw.Start();
            DateTime dateTime = DateTime.Now;
            var      id       = context.JobDetail.JobDataMap.GetIntValue("ID");
            //  var RequestUrl = context.JobDetail.JobDataMap.GetString("RequestUrl");

            JobEntity job = await _jobService.GetAsync(id);

            AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;

            if (job == null)
            {
                await _jobRunLogService.InsertAsync(new JobRunLogEntity()
                {
                    JobGroup = trigger.Group, JobName = trigger.Name, StartTime = DateTime.Now, Succ = false, Exception = "未到找作业或可能被移除"
                });

                return;
            }
            Utility.FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", $"作业[{job.Name}]开始:{ DateTime.Now:yyyy-MM-dd HH:mm:sss}", true);
            if (string.IsNullOrEmpty(job.RequestUrl) || job.RequestUrl == "/")
            {
                Utility.FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", $"{ DateTime.Now:yyyy-MM-dd HH:mm:sss}未配置url,", true);
                await _jobRunLogService.InsertAsync(new JobRunLogEntity()
                {
                    JobGroup = trigger.Group, JobName = trigger.Name, StartTime = DateTime.Now, Succ = false, Exception = "未配置url"
                });

                return;
            }
            try
            {
                string httpMessage = "";
                var    client      = _clientFactory.CreateClient();
                var    request     = new HttpRequestMessage(job.RequestType?.ToLower() == "get" ? HttpMethod.Get : HttpMethod.Post, job.RequestUrl);
                Dictionary <string, string> headers = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(job.AuthKey) &&
                    !string.IsNullOrEmpty(job.AuthValue))
                {
                    headers.Add(job.AuthKey.Trim(), job.AuthValue.Trim());
                }
                if (headers != null && headers.Count > 0)
                {
                    foreach (var header in headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }
                var response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    httpMessage = await response.Content.ReadAsStringAsync();
                }
                sw.Stop();
                await _jobRunLogService.InsertAsync(new JobRunLogEntity()
                {
                    JobGroup = job.Group, JobName = job.Name, StartTime = DateTime.Now, Succ = response.IsSuccessStatusCode, Exception = response.IsSuccessStatusCode?httpMessage: response.ReasonPhrase, RequestMessage = response.ToJson(), StatusCode = (int)response.StatusCode, TotalSeconds = (int)sw.ElapsedMilliseconds
                });

                string logContent = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}_{dateTime:yyyy-MM-dd HH:mm:ss}_{(string.IsNullOrEmpty(httpMessage) ? "" : httpMessage)}\r\n";
                Utility.FileHelper.WriteFile(FileQuartz.LogPath + job.Group + "\\", $"{job.Name}.txt", logContent, true);
                Console.WriteLine(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + httpMessage);
            }
            catch (Exception ex)
            {
                await _jobRunLogService.InsertAsync(new JobRunLogEntity()
                {
                    JobGroup = job.Group, JobName = job.Name, StartTime = DateTime.Now, Succ = false, Exception = ex.Message, TotalSeconds = (int)sw.ElapsedMilliseconds
                });
            }
        }
示例#24
0
 public void SetUp()
 {
     trigger = new TestTrigger();
 }
 private string getMisfireInstructionText(AbstractTrigger trigger)
 {
     if (trigger is CronTriggerImpl)
     {
         return getCronTriggerMisfireInstructionText(trigger.MisfireInstruction);
     }
     return getSimpleTriggerMisfireInstructionText(trigger.MisfireInstruction);
 }
示例#26
0
        public Task Execute(IJobExecutionContext context)
        {
            DateTime          dateTime          = DateTime.Now;
            YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
            SysSetting        sysSetting        = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>();
            Stopwatch         stopwatch         = new Stopwatch();

            stopwatch.Start();
            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            string          sqlWhere    = string.Format("Id='{0}' and GroupName='{1}'", trigger.Name, trigger.Group);
            TaskManager     taskManager = iService.GetWhere(sqlWhere);

            if (taskManager == null)
            {
                FileQuartz.WriteErrorLog($"任务不存在");
                return(Task.Delay(1));
            }
            try
            {
                string msg = $"开始时间:{dateTime.ToString("yyyy-MM-dd HH:mm:ss ffff")}";
                //记录任务执行记录
                iService.RecordRun(taskManager.Id, JobAction.开始, true, msg);
                //初始化任务日志
                FileQuartz.InitTaskJobLogPath(taskManager.Id);
                var jobId = context.MergedJobDataMap.GetString("OpenJob");
                //todo:这里可以加入自己的自动任务逻辑
                Log4NetHelper.Info(DateTime.Now.ToString() + "执行任务");


                stopwatch.Stop();
                string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n";
                iService.RecordRun(taskManager.Id, JobAction.结束, true, content);
                if ((MsgType)taskManager.SendMail == MsgType.All)
                {
                    string emailAddress = sysSetting.Email;
                    if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                    {
                        emailAddress = taskManager.EmailAddress;
                    }

                    List <string> recipients = new List <string>();
                    recipients = emailAddress.Split(",").ToList();
                    var mailBodyEntity = new MailBodyEntity()
                    {
                        Body       = msg + content + ",请勿回复本邮件",
                        Recipients = recipients,
                        Subject    = taskManager.TaskName
                    };
                    SendMailHelper.SendMail(mailBodyEntity);
                }
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n";
                iService.RecordRun(taskManager.Id, JobAction.结束, false, content + ex.Message);
                FileQuartz.WriteErrorLog(ex.Message);
                if ((MsgType)taskManager.SendMail == MsgType.Error || (MsgType)taskManager.SendMail == MsgType.All)
                {
                    string emailAddress = sysSetting.Email;
                    if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                    {
                        emailAddress = taskManager.EmailAddress;
                    }

                    List <string> recipients = new List <string>();
                    recipients = emailAddress.Split(",").ToList();
                    var mailBodyEntity = new MailBodyEntity()
                    {
                        Body       = "处理失败," + ex.Message + ",请勿回复本邮件",
                        Recipients = recipients,
                        Subject    = taskManager.TaskName
                    };
                    SendMailHelper.SendMail(mailBodyEntity);
                }
            }

            return(Task.Delay(1));
        }
示例#27
0
 //执行感应算法检测是否可以感知到触发器
 public abstract bool Percept(AbstractTrigger trigger);
示例#28
0
 /// <summary>
 /// 移除触发
 /// </summary>
 /// <param name="trigger"></param>
 public void RemoveTrigger(AbstractTrigger trigger)
 {
     listTrigger.Remove(trigger);
 }
 private void addCommonTriggerData(XNamespace ns, XElement rootTriggerElement, AbstractTrigger trigger)
 {
     rootTriggerElement.Add(
         new XElement(ns + "name", trigger.Key.Name)
         , new XElement(ns + "group", trigger.Key.Group)
         , new XElement(ns + "description", trigger.Description)
         , new XElement(ns + "misfire-instruction", getMisfireInstructionText(trigger))
         //, new XElement(ns + "volatile", trigger.Volatile)
         , new XElement(ns + "job-name", trigger.JobName)
         , new XElement(ns + "job-group", trigger.JobGroup)
         );
 }
 public void SetUp()
 {
     trigger = new TestTrigger();
 }
示例#31
0
 /// <summary>
 /// 添加触发
 /// </summary>
 /// <param name="trigger"></param>
 public void AddTrigger(AbstractTrigger trigger)
 {
     listTrigger.Add(trigger);
 }
示例#32
0
        /// <summary>
        /// 执行远程接口url的定时任务
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
            SysSetting        sysSetting        = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>();
            Stopwatch         stopwatch         = new Stopwatch();

            stopwatch.Start();
            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            string          sqlWhere    = string.Format("Id='{0}' and GroupName='{1}'", trigger.Name, trigger.Group);
            TaskManager     taskManager = iService.GetWhere(sqlWhere);
            string          httpMessage = "";

            if (taskManager == null)
            {
                FileQuartz.WriteErrorLog($"任务不存在");
                return(Task.Delay(1));
            }
            FileQuartz.InitTaskJobLogPath(taskManager.Id);
            string msg = $"开始时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}";

            //记录任务执行记录
            iService.RecordRun(taskManager.Id, JobAction.开始, true, msg);
            if (string.IsNullOrEmpty(taskManager.JobCallAddress) || taskManager.JobCallAddress == "/")
            {
                FileQuartz.WriteErrorLog($"{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}未配置任务地址,");
                iService.RecordRun(taskManager.Id, JobAction.结束, false, "未配置任务地址");
                return(Task.Delay(1));
            }
            try
            {
                Dictionary <string, string> header = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(taskManager.JobCallParams))
                {
                    httpMessage = HttpRequestHelper.HttpPost(taskManager.JobCallAddress, taskManager.JobCallParams, null, header);
                }
                else
                {
                    httpMessage = HttpRequestHelper.HttpGet(taskManager.JobCallAddress);
                }
                stopwatch.Stop();
                string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒,消息:{httpMessage??"OK"}\r\n";
                iService.RecordRun(taskManager.Id, JobAction.结束, true, content);
                if ((MsgType)taskManager.SendMail == MsgType.All)
                {
                    string emailAddress = sysSetting.Email;
                    if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                    {
                        emailAddress = taskManager.EmailAddress;
                    }

                    List <string> recipients = new List <string>();
                    recipients = taskManager.EmailAddress.Split(",").ToList();
                    //recipients.Add(taskManager.EmailAddress);
                    var mailBodyEntity = new MailBodyEntity()
                    {
                        Body       = content + "\n\r请勿直接回复本邮件!",
                        Recipients = recipients,
                        Subject    = taskManager.TaskName,
                    };
                    SendMailHelper.SendMail(mailBodyEntity);
                }
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n";
                iService.RecordRun(taskManager.Id, JobAction.结束, false, content + ex.Message);
                FileQuartz.WriteErrorLog(ex.Message);
                if ((MsgType)taskManager.SendMail == MsgType.Error || (MsgType)taskManager.SendMail == MsgType.All)
                {
                    string emailAddress = sysSetting.Email;
                    if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                    {
                        emailAddress = taskManager.EmailAddress;
                    }
                    List <string> recipients = new List <string>();
                    recipients = emailAddress.Split(",").ToList();
                    var mailBodyEntity = new MailBodyEntity()
                    {
                        Body       = ex.Message + "\n\r请勿直接回复本邮件!",
                        Recipients = recipients,
                        Subject    = taskManager.TaskName,
                    };
                    SendMailHelper.SendMail(mailBodyEntity);
                }
            }

            return(Task.Delay(1));
        }
示例#33
0
        public static (IList <object>, IList <object>) TriggerCheck(RecipientState state, AgentTriggerPair pair, AbstractTrigger message)
        {
            ITriggeredAction func = state.TriggerToAction[pair];

            (IList <object>, IList <object>)result = func.Execute(state, message);

            return(result.Item1 ?? new List <object>(), result.Item2 ?? new List <object>());
        }