public async Task <ActionResult <ApiResponse> > DeleteHelloJob([FromBody] ScheduleEntity scheduleEntity)
        {
            var result = new ApiResponse();

            try
            {
                var res = await _helloJobService.RemoveScheduleJobAsync(scheduleEntity);

                if (res)
                {
                    result.Message = "删除成功";
                }
                else
                {
                    result.Message = "删除失败";
                }
            }
            catch (Exception ex)
            {
                result.Code    = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return(result);
        }
        public ScheduleEntity MapToScheduleEntity(ScheduleDataDTO source, ScheduleEntity target = null)
        {
            if (source == null)
            {
                return(null);
            }
            if (target == null)
            {
                GetScheduleEntity(source);
            }

            if (!MapToRevision(source, target))
            {
                return(target);
            }

            target.CreatedByUserId      = source.CreatedByUserId;
            target.LastModifiedByUserId = source.LastModifiedByUserId;
            target.Name = source.Name;
            MapCollection(source.Sessions, target.Sessions, (src, trg) =>
            {
                if (src is RaceSessionDataDTO raceSession)
                {
                    return(MapToRaceSessionEntity(raceSession, trg as RaceSessionEntity));
                }

                return(MapToSessionBaseEntity(src, trg));
            }, x => x.SessionId);

            return(target);
        }
Exemplo n.º 3
0
 /// <summary>
 /// This method is only for paramteter customizing (merge with Schedule(string name, ?)
 /// TaskName should be preinitialized and point to existing named tp in container.
 /// </summary>
 /// <param name="tp"></param>
 /// <param name="parallelism"></param>
 /// <param name="dueInSeconds"></param>
 protected void Schedule(TaskParameters tp,
                         ScheduleTaskParallelism parallelism = ScheduleTaskParallelism.AllowOthers,
                         int dueInSeconds = 0)
 {
     lock (runningTasks)
     {
         if (!IsStarted)
         {
             throw new InvalidOperationException("Task scheduler is not running");
         }
         log.Info("Scheduling " + tp);
         var entity = new ScheduleEntity()
         {
             NextExecution = DateTime.MaxValue,
             Parallelism   = parallelism,
             TaskName      = tp.TaskName,
         };
         lock (repoLocker)
         {
             repo.Save(entity);
             repo.LoadSettingsIfNull(entity);
             foreach (KeyValuePair <string, object> setting in tp.Settings)
             {
                 entity.Settings.AddEntry(setting.Key, setting.Value);
             }
             entity.NextExecution = DateTime.Now.AddSeconds(Math.Max(0, dueInSeconds));
             repo.Update(entity);
         }
     }
 }
Exemplo n.º 4
0
        public async Task <ApiResult <string> > AddJob([FromBody] ScheduleEntity entity)
        {
            var res = await _scheduler.AddScheduleJobAsync(entity);

            if (res.statusCode == 200)
            {
                var redisTask = await _cache.GetAsync <List <ScheduleEntity> >(KeyHelper.TaskSchedulerList);

                if (redisTask == null)
                {
                    //实例数组
                    redisTask = new List <ScheduleEntity>();
                }

                entity.BeginTime   = DateTime.Now.AddYears(-1);
                entity.EndTime     = DateTime.Now.AddYears(30);
                entity.TriggerType = TriggerTypeEnum.Cron;
                entity.RequestType = RequestTypeEnum.Get;

                redisTask.Add(entity);

                await _cache.SetAsync(KeyHelper.TaskSchedulerList, redisTask);
            }
            return(res);
        }
Exemplo n.º 5
0
        // [ApiParamValidation]
        public ServiceResponseMessage Create([FromForm] ScheduleInfo task)
        {
            ScheduleEntity model = new ScheduleEntity
            {
                AssemblyName     = task.AssemblyName,
                ClassName        = task.ClassName,
                CreateTime       = DateTime.Now,
                CronExpression   = task.CronExpression,
                EndDate          = task.EndDate,
                Remark           = task.Remark,
                StartDate        = task.StartDate,
                Title            = task.Title,
                Status           = (int)ScheduleStatus.Stop,
                CustomParamsJson = task.CustomParamsJson,
                RunLoop          = task.RunLoop,
                TotalRunCount    = 0,
                CreateUserName   = task.CreateUserName
            };
            var result = _scheduleService.Add(model, task.Keepers, task.Nexts, task.Executors);

            if (result.Status == ResultStatus.Success)
            {
                if (task.RunNow)
                {
                    var start = _scheduleService.Start(model);
                    return(ApiResponse(ResultStatus.Success, "任务创建成功!启动状态为:" + (start.Status == ResultStatus.Success ? "成功" : "失败"), model.Id));
                }
            }
            return(result);
        }
Exemplo n.º 6
0
 public async Task <BaseResult> AddJob([FromBody] ScheduleEntity entity)
 {
     if (ConfigurationManager.GetTryConfig("EnvironmentalRestrictions", "false") == "true")
     {
         if (entity.TriggerType == TriggerTypeEnum.Simple &&
             entity.IntervalSecond.HasValue &&
             entity.IntervalSecond <= 10)
         {
             return(new BaseResult()
             {
                 Code = 403,
                 Msg = "当前环境不允许低于10秒内循环执行任务!"
             });
         }
         else if (entity.TriggerType == TriggerTypeEnum.Cron &&
                  entity.Cron == "* * * * * ?")
         {
             return(new BaseResult()
             {
                 Code = 403,
                 Msg = "当前环境不允许过频繁执行任务!"
             });
         }
     }
     return(await scheduler.AddScheduleJobAsync(entity));
 }
Exemplo n.º 7
0
        private static async Task LoadPluginFile(SmDbContext db, ScheduleEntity model)
        {
            var master = db.ServerNodes.FirstOrDefault(x => x.NodeType == "master");

            if (master == null)
            {
                throw new InvalidOperationException("master not found.");
            }
            var sourcePath = $"{master.AccessProtocol}://{master.Host}/static/downloadpluginfile?pluginname={model.AssemblyName}";
            var zipPath    = $"{ConfigurationCache.PluginPathPrefix}\\{model.AssemblyName}.zip".ToPhysicalPath();
            var pluginPath = $"{ConfigurationCache.PluginPathPrefix}\\{model.Id}".ToPhysicalPath();

            using (WebClient client = new WebClient())
            {
                try
                {
                    await client.DownloadFileTaskAsync(new Uri(sourcePath), zipPath);
                }
                catch (Exception ex)
                {
                    LogHelper.Warn($"下载程序包异常,地址:{sourcePath}", model.Id);
                    throw ex;
                }
            }
            //将指定 zip 存档中的所有文件都解压缩到各自对应的目录下
            ZipFile.ExtractToDirectory(zipPath, pluginPath, true);
            System.IO.File.Delete(zipPath);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 运行指定的计划(泛型指定IJob实现类)
        /// </summary>
        /// <param name="jobGroup">任务分组</param>
        /// <param name="jobName">任务名称</param>
        /// <returns></returns>
        public async Task <BaseQuartzNetResult> RunScheduleJob <V>(ScheduleEntity scheduleModel) where V : IJob
        {
            BaseQuartzNetResult result;
            //添加任务
            var addResult = AddScheduleJob <V>(scheduleModel).Result;

            if (addResult.Code == 200)
            {
                //用给定的密钥恢复(取消暂停)IJobDetail
                await(await Scheduler()).ResumeJob(new JobKey(scheduleModel.JobName, scheduleModel.JobGroup));
                result = new BaseQuartzNetResult
                {
                    Code = 200,
                    Msg  = "启动成功"
                };
            }
            else
            {
                result = new BaseQuartzNetResult
                {
                    Code = -1,
                    Msg  = addResult.Msg
                };
            }
            return(result);
        }
Exemplo n.º 9
0
        public async Task TestPostAsync()
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("Authorization", "QPWBVpMZP+DHWmn502ebwlr4FI21zZrVuk8nHuFrTPQ=");

            var msg2 = await HttpHelper.Instance.PostAsync("http://localhost:60156/api/InspectionOrder/GenerateInspectionOrderJob", "", dic);

            var msg = await HttpHelper.Instance.PostAsync("http://localhost:60156/api/MaintenanceOrder/GenerateMaintenanceOrderJob", "", dic);


            var entity = new ScheduleEntity();

            entity.TriggerType    = TriggerTypeEnum.Simple;
            entity.JobName        = "JobNameBenny";
            entity.JobGroup       = "JobGroupBenny";
            entity.IntervalSecond = 12;
            var addUrl = httpBase + "/api/Job/AddJob";
            //添加测试数据
            var resultStr = await HttpHelper.Instance.PostAsync(addUrl, JsonConvert.SerializeObject(entity));

            var addResult = JsonConvert.DeserializeObject <BaseResult>(resultStr.Content.ReadAsStringAsync().Result);

            //验证
            Assert.True(addResult.Code == 200);

            //删除测试数据
            var key          = new JobKey(entity.JobName, entity.JobGroup);
            var delUrl       = httpBase + "/api/Job/RemoveJob";
            var delResultStr = await HttpHelper.Instance.PostAsync(delUrl, JsonConvert.SerializeObject(key));

            var delResult = JsonConvert.DeserializeObject <BaseResult>(delResultStr.Content.ReadAsStringAsync().Result);

            Assert.True(delResult.Code == 200);
        }
Exemplo n.º 10
0
 /// <summary>
 /// 创建类型Simple的触发器
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 private ITrigger CreateSimpleTrigger(ScheduleEntity entity)
 {
     //作业触发器
     if (entity.RunTimes.HasValue && entity.RunTimes > 0)
     {
         return(TriggerBuilder.Create()
                .WithIdentity(entity.JobName, entity.JobGroup)
                .StartAt(entity.BeginTime) //开始时间
                .EndAt(entity.EndTime)     //结束数据
                .WithSimpleSchedule(x =>
         {
             x.WithIntervalInSeconds(entity.IntervalSecond.Value) //执行时间间隔,单位秒
             .WithRepeatCount(entity.RunTimes.Value)              //执行次数、默认从0开始
             .WithMisfireHandlingInstructionFireNow();
         })
                .ForJob(entity.JobName, entity.JobGroup)//作业名称
                .Build());
     }
     else
     {
         return(TriggerBuilder.Create()
                .WithIdentity(entity.JobName, entity.JobGroup)
                .StartAt(entity.BeginTime) //开始时间
                .EndAt(entity.EndTime)     //结束数据
                .WithSimpleSchedule(x =>
         {
             x.WithIntervalInSeconds(entity.IntervalSecond.Value) //执行时间间隔,单位秒
             .RepeatForever()                                     //无限循环
             .WithMisfireHandlingInstructionFireNow();
         })
                .ForJob(entity.JobName, entity.JobGroup)//作业名称
                .Build());
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// 查询任务
        /// </summary>
        /// <param name="jobGroup"></param>
        /// <param name="jobName"></param>
        /// <returns></returns>
        public async Task <ScheduleEntity> QueryJobAsync(string jobGroup, string jobName)
        {
            var entity    = new ScheduleEntity();
            var jobKey    = new JobKey(jobName, jobGroup);
            var jobDetail = await Scheduler.GetJobDetail(jobKey);

            var triggersList = await Scheduler.GetTriggersOfJob(jobKey);

            var triggers        = triggersList.AsEnumerable().FirstOrDefault();
            var intervalSeconds = (triggers as SimpleTriggerImpl)?.RepeatInterval.TotalSeconds;

            entity.RequestUrl     = jobDetail.JobDataMap.GetString(Constant.REQUESTURL);
            entity.BeginTime      = triggers.StartTimeUtc.LocalDateTime;
            entity.EndTime        = triggers.EndTimeUtc?.LocalDateTime;
            entity.IntervalSecond = intervalSeconds.HasValue ? Convert.ToInt32(intervalSeconds.Value) : 0;
            entity.JobGroup       = jobGroup;
            entity.JobName        = jobName;
            entity.JobType        = jobDetail.JobDataMap.GetString(Constant.REQUESTURL) == null ? 1 : 0;
            entity.AssemblyName   = jobDetail.JobDataMap.GetString(Constant.ASSEMBLYNAME);
            entity.ClassName      = jobDetail.JobDataMap.GetString(Constant.CLASSNAME);
            entity.Cron           = (triggers as CronTriggerImpl)?.CronExpressionString;
            entity.RunTimes       = (triggers as SimpleTriggerImpl)?.RepeatCount;
            entity.TriggerType    = triggers is SimpleTriggerImpl ? 0 : 1;
            //entity.RequestType = (RequestTypeEnum)int.Parse(jobDetail.JobDataMap.GetString(Constant.REQUESTTYPE));
            //entity.RequestParameters = jobDetail.JobDataMap.GetString(Constant.REQUESTPARAMETERS);
            entity.Description = jobDetail.Description;
            return(entity);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 修改任务
        /// </summary>
        /// <param name="schedule"></param>
        /// <returns></returns>
        public IActionResult ModifyJob(ScheduleEntity schedule)
        {
            var res    = SchedulerCenter.Instance.StopOrDelScheduleJobAsync(schedule.JobGroup, schedule.JobName, true);
            var result = new BaseResult();

            if (schedule.JobType == 0)
            {
                result = SchedulerCenter.Instance.AddScheduleJobAsync <HttpJobTask>(schedule).Result;
            }
            else
            {
                result = SchedulerCenter.Instance.AddScheduleJobAsync(schedule).Result;
            }
            if (result.Code == MsgCode.Success)
            {
                return(Json(new BaseResult()
                {
                    Code = MsgCode.Success,
                    Msg = "修改计划任务成功"
                }, new Newtonsoft.Json.JsonSerializerSettings()
                {
                    DateFormatString = "yyyy-MM-dd HH:mm:ss"
                }));
            }
            else
            {
                return(Json(result, new Newtonsoft.Json.JsonSerializerSettings()
                {
                    DateFormatString = "yyyy-MM-dd HH:mm:ss"
                }));
            }
        }
Exemplo n.º 13
0
        private async Task <ScheduleEntity> QueryJobAsync(string jobGroup, string jobName)
        {
            var entity    = new ScheduleEntity();
            var jobKey    = new JobKey(jobName, jobGroup);
            var jobDetail = await this.scheduler.GetJobDetail(jobKey);

            var triggersList = await this.scheduler.GetTriggersOfJob(jobKey);

            var triggers        = triggersList.AsEnumerable().FirstOrDefault();
            var intervalSeconds = (triggers as SimpleTriggerImpl)?.RepeatInterval.TotalSeconds;

            entity.RequestUrl        = jobDetail.JobDataMap.GetString(Constant.RequestUrl);
            entity.BeginTime         = triggers.StartTimeUtc.LocalDateTime;
            entity.EndTime           = triggers.EndTimeUtc?.LocalDateTime;
            entity.IntervalSecond    = intervalSeconds.HasValue ? Convert.ToInt32(intervalSeconds.Value) : 0;
            entity.JobGroup          = jobGroup;
            entity.JobName           = jobName;
            entity.Cron              = (triggers as CronTriggerImpl)?.CronExpressionString;
            entity.RunTimes          = (triggers as SimpleTriggerImpl)?.RepeatCount;
            entity.TriggerType       = triggers is SimpleTriggerImpl ? TriggerTypeEnum.Simple : TriggerTypeEnum.Cron;
            entity.RequestType       = (HttpMethod)int.Parse(jobDetail.JobDataMap.GetString(Constant.RequestType));
            entity.RequestParameters = jobDetail.JobDataMap.GetString(Constant.RequestParameters);
            entity.Headers           = jobDetail.JobDataMap.GetString(Constant.Headers);
            entity.MailMessage       = (MailMessageEnum)int.Parse(jobDetail.JobDataMap.GetString(Constant.MailMessage) ?? "0");
            entity.Description       = jobDetail.Description;
            return(entity);
        }
        public static void Initialize()
        {
            var scheduleEntity = new ScheduleEntity()
            {
                JobId     = 1,
                JobGroup  = "calender01",
                JobName   = "calender01",
                Cron      = "0/10 * * * * ? ",
                BeginTime = DateTime.Now,
                EndTime   = DateTime.MaxValue,
            };

            scheduleEntity.Agrs = new Dictionary <string, object> {
                { "orderId", 1 }
            };

            List <ScheduleEntity> scheduleEntities = new List <ScheduleEntity>()
            {
                scheduleEntity
            };

            ScheduleManager.Instance.AddScheduleList(scheduleEntities);

            SchedulerCenter.Instance.RunScheduleJob <ScheduleManager, CalendarJob>(scheduleEntity.JobGroup, scheduleEntity.JobName).GetAwaiter();
        }
Exemplo n.º 15
0
        /// <summary>
        /// 删除schedule
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_schedule_delete_Click(object sender, EventArgs e)
        {
            if (this.dgv_schedule.SelectedRows.Count == 0)
            {
                MessageBox.Show(this, "尚未选择要删除的事项", "数据同步");
                return;
            }

            DataGridViewRow row            = this.dgv_schedule.SelectedRows[0];
            string          scheduleID     = row.Cells[0].Value.ToString();
            string          scheduleName   = row.Cells[2].Value.ToString();
            ScheduleEntity  scheduleEntity = SyncService.Current.ScheduleManager.GetScheduleEntityByID(scheduleID);

            // 询问确认删除吗
            DialogResult result = MessageBox.Show(this,
                                                  "确认删除\"" + scheduleName + "\"的执行时间设置吗?",
                                                  "数据同步",
                                                  MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question,
                                                  MessageBoxDefaultButton.Button2);

            if (result != DialogResult.Yes)
            {
                return;
            }

            // 删除
            SyncService.Current.ScheduleManager.DeleteSchedule(scheduleEntity);

            // 刷新界面Schedule列表
            this.InitialScheduleList();
        }
        public IHttpActionResult Post([FromUri] string referenceId, [FromBody] ScheduleEntity schedule)
        {
            if (string.IsNullOrEmpty(referenceId))
            {
                return(BadRequest(referenceId));
            }

            var user = System.Threading.Thread.CurrentPrincipal as SecurityPrincipal;

            logger.Info($"Schedule created by {user?.ForeName} for {schedule.ResidentId}");

            var resident = this._residentService.GetResident(new Guid(referenceId));

            if (resident == null)
            {
                return(BadRequest("Resident not found"));
            }
            schedule.ResidentId = resident.Id;
            if (schedule.LocalAuthorityId == 0)
            {
                schedule.LocalAuthorityId = resident.LocalAuthorityId;
            }

            if (schedule.Id > 0)
            {
                _scheduleService.UpdateSchedule(schedule);
            }
            else
            {
                this._scheduleService.CreateSchedule(schedule);
            }


            return(Created("", "Saved"));
        }
        public async Task <ActionResult <ApiResponse <ScheduleEntity> > > AddHelloJob([FromBody] ScheduleEntityDTO scheduleEntityDTO)
        {
            var result = new ApiResponse <ScheduleEntity>();

            try
            {
                ScheduleEntity scheduleEntity = new ScheduleEntity
                {
                    JobKey         = Guid.NewGuid().ToString(),
                    JobGroup       = "Hello",
                    TriggerKey     = Guid.NewGuid().ToString(),
                    TriggerGroup   = "Hello",
                    TimeCreate     = DateTime.Now,
                    TimeStart      = scheduleEntityDTO.TimeStart,
                    TimeEnd        = scheduleEntityDTO.TimeEnd,
                    RepeatCount    = scheduleEntityDTO.RepeatCount,
                    RunState       = "未启动",
                    JobDescription = scheduleEntityDTO.JobDescription
                };

                ScheduleEntity scheduleEntityData = await _helloJobService.AddScheduleJob(scheduleEntity);

                result.Message = "添加成功";
                result.Result  = scheduleEntityData;
            }
            catch (Exception ex)
            {
                result.Code    = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return(result);
        }
Exemplo n.º 18
0
        public async Task <ApiResult <string> > ModifyJob([FromBody] ScheduleEntity entity)
        {
            entity.BeginTime   = DateTime.Now.AddYears(-1);
            entity.EndTime     = DateTime.Now.AddYears(30);
            entity.TriggerType = TriggerTypeEnum.Cron;
            entity.RequestType = RequestTypeEnum.Get;

            await _scheduler.StopOrDelScheduleJobAsync(entity.JobGroup, entity.JobName, true);

            //删除Redis里面的任务
            var redisTask = await _cache.GetAsync <List <ScheduleEntity> >(KeyHelper.TaskSchedulerList);

            if (redisTask != null && redisTask.Count > 0)
            {
                var delModel = redisTask.FirstOrDefault(m => m.JobGroup == entity.JobGroup && m.JobName == entity.JobName);
                redisTask.Remove(delModel);
            }
            var res = await _scheduler.AddScheduleJobAsync(entity);

            if (res.statusCode == 200)
            {
                //添加新的任务
                redisTask.Add(entity);
                //保存到Redis中
                await _cache.SetAsync(KeyHelper.TaskSchedulerList, redisTask);
            }
            return(res);
        }
Exemplo n.º 19
0
 /// <summary>运行指定的计划</summary>
 /// <param name="jobGroup"></param>
 /// <param name="jobName"></param>
 /// <returns></returns>
 public StatusResult RunScheduleJob <T, V>(string jobGroup, string jobName) where T : ScheduleManage, new() where V : IJob
 {
     try
     {
         T instance = Activator.CreateInstance <T>();
         ScheduleEntity scheduleModel = instance.GetScheduleModel(jobGroup, jobName);
         if (this.AddScheduleJob <V>(scheduleModel))
         {
             scheduleModel.Status = EnumType.JobStatus.已启用;
             instance.UpdateScheduleStatus(scheduleModel);
             this.Scheduler.ResumeJob(new JobKey(jobName, jobGroup));
             return(new StatusResult()
             {
                 Status = 0,
                 Msg = "启动成功"
             });
         }
         return(new StatusResult()
         {
             Status = -1,
             Msg = "启动失败"
         });
     }
     catch (Exception ex)
     {
         return(new StatusResult()
         {
             Status = -1,
             Msg = "启动失败"
         });
     }
 }
        public void UpdateSchedule(ScheduleEntity schedule)
        {
            string sql = @"UPDATE [dbo].[schedules] 
                            SET
                            [local_authority_id] = @localauthorityid
                           ,[payment_provider_id] = @paymentproviderid
                           ,[payment_type_id] = @paymenttypeid
                           ,[description] = @description
                           ,[schedule_begin_date] = @schedulebegindate
                           ,[schedule_end_date] = @scheduleenddate
                           ,[weekly_fee] = @weeklyfee
                           ,[updated_date] = GETDATE()
                            WHERE id = @id";

            using (IDbConnection conn = new SqlConnection(_connectionString))
            {
                DynamicParameters dp = new DynamicParameters();
                conn.Open();
                dp.Add("id", schedule.Id, DbType.Int32, ParameterDirection.Input);
                dp.Add("localauthorityid", schedule.LocalAuthorityId, DbType.Int32, ParameterDirection.Input);
                dp.Add("paymentproviderid", schedule.PaymentProviderId, DbType.String, ParameterDirection.Input, 80);
                dp.Add("paymenttypeid", schedule.PaymentTypeId, DbType.String, ParameterDirection.Input, 80);
                dp.Add("description", schedule.Description.Trim(), DbType.String, ParameterDirection.Input, 200);
                dp.Add("schedulebegindate", schedule.ScheduleBeginDate, DbType.Date, ParameterDirection.Input, 80);
                dp.Add("scheduleenddate", schedule.ScheduleEndDate, DbType.Date, ParameterDirection.Input, 80);
                dp.Add("weeklyfee", schedule.WeeklyFee, DbType.Decimal, ParameterDirection.Input, 80);

                var result = conn.Execute(sql, dp, commandType: CommandType.Text);
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// 创建类型Simple的触发器
 /// </summary>
 /// <param name="m"></param>
 /// <returns></returns>
 private ITrigger CreateSimpleTrigger(ScheduleEntity m)
 {
     //作业触发器
     if (m.RunTimes > 0)
     {
         return(TriggerBuilder.Create()
                .WithIdentity(m.JobName, m.JobGroup)
                .StartAt(m.BeginTime)                                        //开始时间
                .EndAt(m.EndTime)                                            //结束数据
                .WithSimpleSchedule(x => x
                                    .WithIntervalInSeconds(m.IntervalSecond) //执行时间间隔,单位秒
                                    .WithRepeatCount(m.RunTimes))            //执行次数、默认从0开始
                .ForJob(m.JobName, m.JobGroup)                               //作业名称
                .Build());
     }
     else
     {
         return(TriggerBuilder.Create()
                .WithIdentity(m.JobName, m.JobGroup)
                .StartAt(m.BeginTime)                                        //开始时间
                .EndAt(m.EndTime)                                            //结束数据
                .WithSimpleSchedule(x => x
                                    .WithIntervalInSeconds(m.IntervalSecond) //执行时间间隔,单位秒
                                    .RepeatForever())                        //无限循环
                .ForJob(m.JobName, m.JobGroup)                               //作业名称
                .Build());
     }
 }
Exemplo n.º 22
0
        public Guid AddSchedule(ScheduleEntity scheduleEntity)
        {
            var schedule = _databaseContext.Schedules.Add(scheduleEntity);

            _databaseContext.SaveChanges();

            return(schedule.Entity.Id);
        }
 public async Task <MessageModel> Update(ScheduleEntity model)
 {
     if (model.IntervalSecond == 0)
     {
         model.IntervalSecond = 1;
     }
     return(new MessageModel(await _ScheduleEntityServices.Update(model)));
 }
Exemplo n.º 24
0
        public ScheduleDTO FindOne(long id)
        {
            ScheduleDTO    dto    = new ScheduleDTO();
            ScheduleEntity entity = _humanManagerContext.Schedules.Find(id);

            dto = _mapper.Map <ScheduleDTO>(entity);
            return(dto);
        }
Exemplo n.º 25
0
 public static ScheduleViewModel FromScheduleEntity(ScheduleEntity entity)
 {
     return(new ScheduleViewModel
     {
         Id = entity.Id,
         ExampleDateTime = entity.ExampleDateTime,
     });
 }
Exemplo n.º 26
0
        public ActionResult <Api <ScheduleDTO> > Save(ScheduleEntity schedule)
        {
            ScheduleDTO dto = _scheduleService.Save(schedule);

            Api <ScheduleDTO> result = new Api <ScheduleDTO>(200, dto, "Success", null);

            return(Ok(result));
        }
Exemplo n.º 27
0
        /// <summary>
        /// 添加一个任务
        /// </summary>
        /// <param name="model"></param>
        /// <param name="keepers"></param>
        /// <param name="nexts"></param>
        /// <param name="executors"></param>
        /// <returns></returns>
        public ServiceResponseMessage Add(ScheduleEntity model, List <int> keepers, List <Guid> nexts, List <string> executors = null)
        {
            model.CreateTime = DateTime.Now;
            var user = _repositoryFactory.SystemUsers.FirstOrDefault(x => x.UserName == model.CreateUserName);

            if (user != null)
            {
                model.CreateUserId = user.Id;
            }
            _repositoryFactory.Schedules.Add(model);
            _repositoryFactory.ScheduleLocks.Add(new ScheduleLockEntity {
                ScheduleId = model.Id, Status = 0
            });

            if (executors == null || !executors.Any())
            {
                //没有指定worker就根据权重选择2个
                executors = _repositoryFactory.ServerNodes.Where(x => x.NodeType == "worker" && x.Status == 2)
                            .OrderByDescending(x => x.Priority).Take(2).Select(x => x.NodeName).ToList();
            }
            if (executors.Any())
            {
                _repositoryFactory.ScheduleExecutors.AddRange(executors.Select(x => new ScheduleExecutorEntity
                {
                    ScheduleId = model.Id,
                    WorkerName = x
                }));
            }

            if (_unitOfWork.Commit() > 0)
            {
                bool extended = false;
                if (keepers != null && keepers.Count > 0)
                {
                    extended = true;
                    _repositoryFactory.ScheduleKeepers.AddRange(keepers.Select(x => new ScheduleKeeperEntity
                    {
                        ScheduleId = model.Id,
                        UserId     = x
                    }));
                }
                if (nexts != null && nexts.Count > 0)
                {
                    extended = true;
                    _repositoryFactory.ScheduleReferences.AddRange(nexts.Select(x => new ScheduleReferenceEntity
                    {
                        ScheduleId = model.Id,
                        ChildId    = x
                    }));
                }
                if (extended)
                {
                    _unitOfWork.Commit();
                }
                return(ServiceResult(ResultStatus.Success, "任务创建成功!"));
            }
            return(ServiceResult(ResultStatus.Failed, "数据保存失败!"));
        }
Exemplo n.º 28
0
        private bool EnqueueScheduledTaskAndRecalculateNextTime(ScheduleEntity scheduleEntity, string reasonToEnqueue, Func <ScheduledTask, ScheduledTask> caluculateNext, DbConnection connection)
        {
            var scheduledTask = ScheduleEntity.ToScheduleTask(scheduleEntity);

            //if calculate delegate exists, calculate next invocation and save, otherwise (manual trigger), skip
            if (caluculateNext != null)
            {
                scheduledTask = caluculateNext(scheduledTask);
                scheduleEntity.LastInvocation = scheduledTask.LastInvocation;
                scheduleEntity.NextInvocation = scheduledTask.NextInvocation;
                this._queryService.UpdateScheduledItem(scheduleEntity, t => new { t.LastInvocation, t.NextInvocation }, connection);
            }

            //if job scheduled
            if (!string.IsNullOrEmpty(scheduleEntity.JobInvocationData))
            {
                var insertedJob = JobEntity.FromScheduleEntity(scheduledTask);
                insertedJob.ScheduleName = scheduleEntity.Name;
                var jobId   = this._queryService.InsertJob(insertedJob, connection);
                var stateId = this._queryService.InsertJobState(
                    StateEntity.FromIState(new EnqueuedState()
                {
                    EnqueuedAt = DateTime.UtcNow, Queue = scheduledTask.Job.QueueName, Reason = reasonToEnqueue
                },
                                           insertedJob.Id),
                    connection);
                this._queryService.SetJobState(jobId, stateId, EnqueuedState.DefaultName, connection);
                this._queryService.InsertJobToQueue(jobId, scheduledTask.Job.QueueName, connection);
                return(true);
            }
            //if workflow scheduled
            else if (!string.IsNullOrEmpty(scheduleEntity.WorkflowInvocationData))
            {
                var rootJobs = scheduledTask.Workflow.GetRootJobs().ToDictionary(t => t.TempId, null);
                scheduledTask.Workflow.SaveWorkflow((workflowJob) => {
                    workflowJob.QueueJob.ScheduleName = scheduleEntity.Name;
                    return(CreateAndEnqueueJob(
                               queueJob: workflowJob.QueueJob,
                               state: rootJobs.ContainsKey(workflowJob.TempId) ?
                               new EnqueuedState()
                    {
                        EnqueuedAt = DateTime.UtcNow, Queue = workflowJob.QueueJob.QueueName, Reason = reasonToEnqueue
                    } as IState
                            : new AwaitingState()
                    {
                        Reason = "Waiting for other job/s to finish.", CreatedAt = DateTime.UtcNow
                    } as IState,
                               connection: connection
                               ));
                });
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 29
0
 /// <summary>
 ///     Mapea un objeto ScheduleEntity en un objeto Schedule
 /// </summary>
 /// <param name="scheduleEntity"></param>
 /// <returns></returns>
 public static Schedule Map(ScheduleEntity scheduleEntity)
 {
     return(new Schedule()
     {
         Id = scheduleEntity.Id,
         Start = scheduleEntity.Start.ToString(@"hh\:mm"),
         End = scheduleEntity.End.ToString(@"hh\:mm")
     });
 }
Exemplo n.º 30
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());
        }
 public List<string> ResolveCore(ScheduleEntity source)
 {
     var sessionUrls = new List<string>();
       foreach (var session in source.SessionUrls)
       {
     sessionUrls.Add(CombineUrl("/" + session));
       }
       return sessionUrls;
 }
Exemplo n.º 32
0
        void Fill(DataTable dt)
        {
            Classes = new Dictionary<DayOfWeek, List<ScheduleEntity>>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Check.CheckRow(dt.Rows[i]))
                {

                    DayOfWeek day = GetDay(dt.Rows[i].ItemArray[0].ToString());
                    var set = Factory.GetSettings();

                        string[] time_start = dt.Rows[i].ItemArray[1].ToString().Split(':');
                        string[] time_finish = dt.Rows[i].ItemArray[2].ToString().Split(':');
                        string name = dt.Rows[i].ItemArray[3].ToString();
                        string type = dt.Rows[i].ItemArray[4].ToString();
                        string adress = dt.Rows[i].ItemArray[5].ToString();
                        string room = dt.Rows[i].ItemArray[6].ToString();
                        string tutor = dt.Rows[i].ItemArray[7].ToString();

                        DateTime today = DateTime.Today;
                        int daysUntil = ((int)day - (int)today.DayOfWeek + 7) % 7;
                        DateTime nextDate = today.AddDays(daysUntil);

                        ScheduleEntity day_classes = new ScheduleEntity()
                        {
                            Start = new DateTime(nextDate.Year, nextDate.Month, nextDate.Day, int.Parse(time_start[0]), int.Parse(time_start[1]), 0),
                            Finish = new DateTime(nextDate.Year, nextDate.Month, nextDate.Day, int.Parse(time_finish[0]), int.Parse(time_finish[1]), 0),
                            Name = name,
                            Type = type,
                            Adress = adress,
                            Room = room,
                            Tutor = tutor,
                            Group = "ББИ145",
                            SubGroup = set.Subgroup,
                            Minor = set.Minor,
                            Priority = 0
                        };

                        if (Classes.ContainsKey(day))
                        {
                            Classes[day].Add(day_classes);
                        }
                        else
                            Classes.Add(day, new List<ScheduleEntity> { day_classes });

                }
            }
        }
Exemplo n.º 33
0
        public Tuple<int, int> Time(ScheduleEntity ent, string time)
        {

            if (ent == null || time == null)
            { throw new ArgumentNullException(); }
            

            string[] st = time.Split(new char[] { ' ' });
            //MessageBox.Show(time);

            int hour = ent.Start.Hour;
            int min = ent.Start.Minute;
           // MessageBox.Show(hour.ToString() + " " + min.ToString()); //CHECK

            int hourGoogle = 0;
            int minGoogle;

            if (time.Contains("day"))
            {
                MessageBox.Show("Please enter address correctly or set alarm manually", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return null;
            }

            if (time.Contains("hour"))
            {
             
                    hourGoogle = Convert.ToInt16(st[0]);
                
                    minGoogle = Convert.ToInt16(st[2]);
   
              // MessageBox.Show(hourGoogle.ToString()+" " + minGoogle.ToString()); //CHECK

            }

            else
            {
                minGoogle = Convert.ToInt16(st[0]);

            }

            string[] timetoready = set.TimeToReady.Split(new char[] { ':' });

            try {
                int readyHour = Convert.ToInt16(timetoready[0]);
                int readyMin = Convert.ToInt16(timetoready[1]);
                //MessageBox.Show(readyHour.ToString() + ":" + readyMin.ToString()); //CHECK


                int finalhour = hour - readyHour- hourGoogle;
                if (finalhour < 0)
                    MessageBox.Show("Oooops! You need more than 24 hours to get to the university. If it is true, please set alarm manualy or write address more correct", "Ooops!", MessageBoxButton.OK, MessageBoxImage.Warning);

                int finalminutes = min- minGoogle - readyMin - 20;

                var finaltime = finalhour * 60 + finalminutes;
                finalhour = (int)(finaltime / 60);
                finalminutes = finaltime - finalhour * 60;
               // MessageBox.Show(finalhour.ToString() + ":" + finalminutes.ToString());//CHECK
            


            return Tuple.Create<int, int>(finalhour, finalminutes);
        }
            catch { MessageBox.Show("here"); throw new ArgumentException(); }
        }
 /// <summary>
 /// This method is only for paramteter customizing (merge with Schedule(string name, ?)
 /// TaskName should be preinitialized and point to existing named tp in container.
 /// </summary>
 /// <param name="tp"></param>
 /// <param name="parallelism"></param>
 /// <param name="dueInSeconds"></param>
 protected void Schedule(TaskParameters tp, 
     ScheduleTaskParallelism parallelism = ScheduleTaskParallelism.AllowOthers, 
     int dueInSeconds = 0)
 {
     lock (runningTasks)
     {
         if (!IsStarted) throw new InvalidOperationException("Task scheduler is not running");
         log.Info("Scheduling "+tp);
         var entity = new ScheduleEntity()
                          {
                              NextExecution = DateTime.MaxValue,
                              Parallelism = parallelism,
                              TaskName = tp.TaskName,
                          };
         lock (repoLocker)
         {
             repo.Save(entity);
             repo.LoadSettingsIfNull(entity);
             foreach (KeyValuePair<string, object> setting in tp.Settings)
             {
                 entity.Settings.AddEntry(setting.Key, setting.Value);
             }
             entity.NextExecution = DateTime.Now.AddSeconds(Math.Max(0, dueInSeconds));
             repo.Update(entity);
         }
     }
 }
        protected void StartTask(ScheduleEntity entity)
        {
            if (isFinishing) return;

            lock (runningTasks)
            {
                entity.ExecutionState = ScheduleExecutionState.Running;
                lock (repoLocker) repo.Update(entity);

                var task = container.Resolve<PersistentSchedulerTask>();
                task.ScriptFinished +=
                    (t, s) =>
                        {
                            var e = (t as PersistentSchedulerTask).Entity;
                            e.LastExecution = DateTime.Now;
                            e.MessageState = s.Flow.MessagesState;
                            if (t.ScheduledScripts.Count == 0 || s.Flow.MessagesState >= ScheduleMessageState.Error)
                            {
                                e.ExecutionState = ScheduleExecutionState.Finished;
                            }
                            else
                            {
                                e.NextExecution = t.ScheduledScripts.First().Date;
                                e.ExecutionState = ScheduleExecutionState.Idle;
                            }
                            //settings should be stored automatically
                            lock (repoLocker) repo.Update(entity);
                        };

                task.TaskName = entity.TaskName;
                task.Entity = entity;
                task.Settings = new EntityTaskSettings(entity.Settings);

                task.Scripts = GetNamedTaskParameter(task.TaskName).Scripts;
                StartTask(task);
            }
        }