//间隔一定时间重复一次执行指定的任务
        public static async void WithInterval()
        {
            //--------------------------------1.准备调度者
            //创建调度器工厂
            ISchedulerFactory factory = new StdSchedulerFactory();
            //创建调度者
            IScheduler scheduler = await factory.GetScheduler();

            //--------------------------------2.准备任务
            //创建任务构造这:JobBuilder
            JobBuilder jobBuilder = JobBuilder.Create <TestJob>();
            //创建任务,定义任务的名字和任务组
            //IJobDetail job = jobBuilder.WithIdentity("job1", "grpup1").Build();
            IJobDetail job1 = jobBuilder.Build();

            //--------------------------------3.准备触发器
            //创建触发器构造者:TriggerBuilder
            TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever());
            //创建触发器,定义触发器的名字和触发组
            //ISimpleTrigger trigger1 = triggerBuilder.WithIdentity("trigger1","group2").Build() as ISimpleTrigger;
            ITrigger trigger = triggerBuilder.Build();


            //--------------------------------4、将任务与触发器添加到调度器中
            await scheduler.ScheduleJob(job1, trigger);

            //开始执行
            await scheduler.Start();
        }
Example #2
0
    public static void CreateJob <T>(JobInfo jInfo, ref IScheduler scheduler) where T : IJob
    {
        JobBuilder jbuilder = JobBuilder.Create <T>();

        jbuilder.WithIdentity(jInfo.JobName, jInfo.GroupName);

        if (jInfo.DataParamters != null && jInfo.DataParamters.Any())
        {
            foreach (var item in jInfo.DataParamters)
            {
                jbuilder.UsingJobData(GetDataMap(item));
            }
        }

        IJobDetail jobDetail = jbuilder.Build();

        TriggerBuilder tBuilder = TriggerBuilder.Create();

        tBuilder.WithIdentity(jInfo.TriggerName, jInfo.GroupName)
        .StartNow()
        .WithCronSchedule(jInfo.CronExpression);
        //.WithSimpleSchedule(x => x
        //    .WithIntervalInSeconds(10)
        //    .RepeatForever());

        ITrigger trigger = tBuilder.Build();

        scheduler.ScheduleJob(jobDetail, trigger);
    }
Example #3
0
        /// <summary>
        /// 删除远程任务
        /// </summary>
        /// <param name="taskid">任务id</param>
        /// <param name="message">返回信息</param>
        /// <returns>是否成功</returns>
        public static async Task<bool> DelRemoteTask(string taskid)
        {
            bool result = false;
            string message = "";
            try
            {
                if (!_taskPool.ContainsKey(taskid))
                {
                    //任务
                    JobBuilder jobBuilder = JobBuilder.Create()
                                            .WithIdentity(taskid);

                    IJobDetail jobDetail = jobBuilder.Build();

                    if (_remoteScheduler.CheckExists(jobDetail.Key).Result)
                    {
                        _remoteScheduler.DeleteJob(jobDetail.Key);
                    }

                    _taskPool.Remove(taskid);
                }                

                message = string.Format("删除远程任务成功:{0}", taskid);
                log.Debug(message);
                result = true;
            }
            catch (QMException ex)
            {
                message = string.Format("删除远程任务失败:{0},{1},{2},{3},{4}", taskid, ex.Message, ex.StackTrace);
                log.Fatal(message);
            }

            return result;
        }
Example #4
0
        //间隔一定时间重复一次执行指定的任务
        public static async void WithInterval()
        {
            //--------------------------------1.准备调度者
            //创建调度器工厂
            ISchedulerFactory factory = new StdSchedulerFactory();
            //创建调度者
            IScheduler scheduler = await factory.GetScheduler();

            //--------------------------------2.准备任务
            //创建任务构造这:JobBuilder
            JobBuilder jobBuilder = JobBuilder.Create <TestJob1>();
            //创建任务,定义任务的名字和任务组
            //IJobDetail job = jobBuilder.WithIdentity("job1", "grpup1").Build();
            IJobDetail job1 = jobBuilder.Build();

            //--------------------------------3.准备触发器
            //创建触发器构造者:TriggerBuilder
            TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(5).WithRepeatCount(2));//此处RepeatForever()为重复无数次,使用.WithRepeatCount()可以设置重复的次数
            //创建触发器,定义触发器的名字和触发组
            ISimpleTrigger trigger = triggerBuilder.WithIdentity("trigger1", "group2").Build() as ISimpleTrigger;

            //--------------------------------4、将任务与触发器添加到调度器中
            await scheduler.ScheduleJob(job1, trigger);

            //开始执行
            await scheduler.Start();

            //调度器延时调度,但是注意,在调度器延时的时候,定时任务可能计时已经开始了,
            //一旦结束调度器的延时,定时任务会把之前延时的时间中应该执行的任务都一次性执行了
            //await scheduler.StartDelayed(TimeSpan.FromSeconds(20));
        }
        protected Job NewJob(Action <JobBuilder> setUp = null)
        {
            JobBuilder jobBuilder = new JobBuilder();

            setUp?.Invoke(jobBuilder);

            return(jobBuilder.Build());
        }
    public PersonBuilder HavingJob(Action <IJobBuilder> configure)
    {
        var builder = new JobBuilder();

        configure(builder);
        Person.Jobs.Add(builder.Build());
        return(this);
    }
        private IJobDetail CreateJobDetail <TJob>() where TJob : IJob
        {
            JobBuilder jobBuilder = JobBuilder.Create();

            jobBuilder.OfType <TJob>();

            return(jobBuilder.Build());
        }
        public ScheduleJobResult ScheduleJob <T>(string jobId, string jobGroup, string cronExpression, Dictionary <string, string> jobData = null, string timeZone = null)
            where T : IJob
        {
            var ret = new ScheduleJobResult();

            // a. build job
            JobBuilder jobBuilder = JobBuilder.Create <T>()
                                    .WithIdentity(jobId, jobGroup);

            if (jobData != null)
            {
                foreach (KeyValuePair <string, string> pair in jobData)
                {
                    jobBuilder.UsingJobData(pair.Key, pair.Value);
                }
            }

            IJobDetail job = jobBuilder.Build();

            ret.Job = job;
            //

            // b. build trigger
            TimeZoneInfo   timeZoneInfo   = string.IsNullOrWhiteSpace(timeZone) ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(timeZone);
            TriggerBuilder triggerBuilder = TriggerBuilder.Create()
                                            .WithIdentity(jobId, jobGroup)
                                            .WithCronSchedule(cronExpression, x => x.InTimeZone(timeZoneInfo));

            if (jobData != null)
            {
                foreach (KeyValuePair <string, string> pair in jobData)
                {
                    jobBuilder.UsingJobData(pair.Key, pair.Value);
                }
            }

            ITrigger trigger = triggerBuilder.Build();

            ret.Trigger = trigger;
            //

            // c. schedule job
            if (trigger.GetNextFiringTimes(DateTimeOffset.Now).FirstOrDefault() == default(DateTime))
            {
                ret.Success = false;

                _log.Info($"Job WILL NEVER START for \"{jobId}\"");
            }
            else
            {
                _scheduler.ScheduleJob(job, trigger).Wait();
                ret.Success = true;

                _log.Debug($"Job scheduled OK for \"{jobId}\"");
            }

            return(ret);
        }
Example #9
0
        public static IJobDetail GetJobDetail()
        {
            //创建一个作业
            JobBuilder jobBuilder = JobBuilder.Create <VoidUnPaidOrderJob>();
            //jobBuilder.WithIdentity("作业名称", "作业组");
            //jobBuilder.UsingJobData("jobSays", "Hello World!");//作业数据传递
            IJobDetail jobDetail = jobBuilder.Build();

            return(jobDetail);
        }
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <typeparam name="TJob"></typeparam>
        /// <param name="configureJob"></param>
        /// <param name="configureTrigger"></param>
        /// <returns></returns>
        public async Task ScheduleAsync <TJob>(Action <JobBuilder> configureJob, Action <TriggerBuilder> configureTrigger) where TJob : IJob
        {
            JobBuilder jobToBuild = JobBuilder.Create <TJob>();

            configureJob(jobToBuild);
            IJobDetail job = jobToBuild.Build();

            TriggerBuilder triggerToBuild = TriggerBuilder.Create();

            configureTrigger(triggerToBuild);
            ITrigger trigger = triggerToBuild.Build();

            await _quartzConfiguration.Scheduler.ScheduleJob(job, trigger);
        }
Example #11
0
        /// <summary>
        /// 添加定时任务
        /// </summary>
        /// <param name="intervalTs">间隔时间</param>
        /// <param name="startAt">第一次执行时间</param>
        /// <param name="repeatCount">重复次数,不填或者为0:不限次</param>
        public static void AddJobExt <T>(this IScheduler scheduler, TimeSpan intervalTs, DateTime?startAt = null, int?repeatCount = null, IDictionary <string, object> jobDataDic = null) where T : IJob
        {
            string jobName     = typeof(T).Name;
            string groupName   = jobName + "Group";
            string triggerName = jobName + "Trigger";

            JobBuilder jobBuilder = JobBuilder.Create <T>().WithIdentity(jobName, groupName);

            if (jobDataDic != null)
            {
                jobBuilder.UsingJobData(new JobDataMap(jobDataDic));
            }

            IJobDetail job = jobBuilder.Build();

            AddJob(scheduler, intervalTs, startAt, repeatCount, groupName, triggerName, job);
        }
Example #12
0
        /// <summary>
        /// Schedule a recurring Task
        /// </summary>
        /// <param name="Task"></param>
        /// <param name="CallBackDelay"></param>
        /// <param name="Parameters"></param>
        /// <returns></returns>
        public static TaskScheduleResult ScheduleRecurringTask(JobBuilder Task, string CronSchedule, Dictionary <string, object> Parameters = null)
        {
            TaskScheduleResult Result = new TaskScheduleResult();
            Guid Id = Guid.NewGuid();

            IJobDetail job     = Task.WithIdentity(Id.ToString(), Task.Build().JobType.Name).Build();
            bool       Success = false;

            try
            {
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
                scheduler.Start();

                string Group = job.JobType.Name;

                JobKey Key = new JobKey(Id.ToString(), Group);


                TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithIdentity(Id.ToString(), Group).WithCronSchedule(
                    CronSchedule,
                    x => x.InTimeZone(TimeZoneInfo.Utc)
                    );

                if (Parameters != null)
                {
                    foreach (var Param in Parameters)
                    {
                        triggerBuilder = triggerBuilder.UsingJobData(Param.Key, Param.Value.ToString());
                    }
                }
                ITrigger trigger = triggerBuilder.ForJob(job).Build();


                var DatetimeOffset = scheduler.ScheduleJob(job, trigger);
                Success          = DatetimeOffset != null ? true : false;
                Result.GroupName = Group;
                Result.Id        = Id.ToString();
            }
            catch (Exception e)
            {
                Success = false;
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "job = " + job.JobType.Name);
            }
            Result.Result = Success;
            return(Result);
        }
        private async Task <List <string> > GetResults(GeneratedSite entity, JobBuilder builder)
        {
            var results = new List <string>();

            var generator = _exportTypeSettings.GetGenerator(entity.ExportFormat);

            if (generator == null)
            {
                throw new Exception("Export format not supported");
            }

            var job    = builder.Build();
            var runner = new JobRunner(generator);

            results.AddRange(await runner.RunJob(job));

            return(results);
        }
        public ScheduleJobResult ScheduleJob <T>(string jobId, string jobGroup, ITrigger trigger, Dictionary <string, string> jobData = null)
            where T : IJob
        {
            var ret = new ScheduleJobResult();

            // a. build job
            JobBuilder jobBuilder = JobBuilder.Create <T>()
                                    .WithIdentity(jobId, jobGroup);

            if (jobData != null)
            {
                foreach (KeyValuePair <string, string> pair in jobData)
                {
                    jobBuilder.UsingJobData(pair.Key, pair.Value);
                }
            }

            IJobDetail job = jobBuilder.Build();

            ret.Job = job;
            //

            // b. use trigger
            ret.Trigger = trigger;
            //

            // c. schedule job
            if (trigger.GetNextFiringTimes(DateTimeOffset.Now).FirstOrDefault() == default(DateTime))
            {
                ret.Success = false;

                _log.Info($"Job WILL NEVER START for \"{jobId}\"");
            }
            else
            {
                _scheduler.ScheduleJob(job, trigger).Wait();
                ret.Success = true;

                _log.Debug($"Job scheduled OK for \"{jobId}\"");
            }

            return(ret);
        }
        public override void Start()
        {
            JobBuilder jobBuilder = JobBuilder.Create <TestJob>();


            IJobDetail testJob = jobBuilder.Build();


            var trigger = TriggerBuilder.Create()
                          .WithIdentity("DeleteGoogleDriveFiles", "DeleteGoogleDriveFiles")
                          .WithCalendarIntervalSchedule(x => x.WithIntervalInHours(1))
                          .WithDescription("trigger")
                          .StartNow()
                          .Build();


            Scheduler.ScheduleJob(testJob, trigger);

            Scheduler.Start();
        }
Example #16
0
        protected void ScheduleJobWithDefaultTrigger <T>(string jobGroupName, string jobName) where T : IJob
        {
            JobBuilder builder = JobBuilder.Create <T>()
                                 .WithIdentity(jobName, jobGroupName)
                                 .WithDescription(jobGroupName + "." + jobName);

            IJobDetail job = builder.Build();

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity(TriggerName, jobGroupName)
                               .StartAt(runTime)
                               .WithSchedule(CalendarIntervalScheduleBuilder.Create().WithIntervalInMinutes(1))
                               .Build();

            _sched.ScheduleJob(job, trigger);

            Context = new SchedulerModel(_sched);
        }
        public void RunNow <T>(string jobId, Dictionary <string, string> jobData = null)
            where T : IJob
        {
            string uid = Guid.NewGuid().ToString();

            // a. build job
            JobBuilder jobBuilder = JobBuilder.Create <T>()
                                    .WithIdentity($"{jobId}_{uid}", "OneTimeJobs");

            if (jobData != null)
            {
                foreach (KeyValuePair <string, string> pair in jobData)
                {
                    jobBuilder.UsingJobData(pair.Key, pair.Value);
                }
            }

            IJobDetail job = jobBuilder.Build();
            //

            // b. build trigger
            TriggerBuilder triggerBuilder = TriggerBuilder.Create()
                                            .WithIdentity($"{jobId}_{uid}", "OneTimeTriggers")
                                            .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).WithRepeatCount(1));

            if (jobData != null)
            {
                foreach (KeyValuePair <string, string> pair in jobData)
                {
                    jobBuilder.UsingJobData(pair.Key, pair.Value);
                }
            }

            ITrigger trigger = triggerBuilder.Build();

            //

            // c. schedule job
            _scheduler.ScheduleJob(job, trigger).Wait();
        }
Example #18
0
        public void CreateContext()
        {
            JobBuilder builder = JobBuilder.Create <T>()
                                 .WithIdentity(JobName, GroupName)
                                 .WithDescription(JobDescription);

            CustomizeJob(builder);

            IJobDetail job = builder.Build();

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity(TriggerName, GroupName)
                               .StartAt(runTime)
                               .WithSchedule(CalendarIntervalScheduleBuilder.Create().WithIntervalInMinutes(1))
                               .Build();

            _sched.ScheduleJob(job, trigger);

            Context = new JobModel(_sched, new JobKey(JobName, GroupName));
        }
Example #19
0
        /// <summary>
        /// 添加定时任务
        /// </summary>
        /// <param name="type">类型:必须继承至IJob</param>
        /// <param name="intervalTs">间隔时间</param>
        /// <param name="startAt">第一次执行时间</param>
        /// <param name="repeatCount">重复次数,不填或者为0:不限次</param>
        public static void AddJobExt(this IScheduler scheduler, Type type, TimeSpan intervalTs, DateTime?startAt = null, int?repeatCount = null, IDictionary <string, object> jobDataDic = null)
        {
            if (!typeof(IJob).IsAssignableFrom(type))
            {
                throw new ArgumentException("传入的类型必须是IJob的派生类!");
            }

            string jobName     = type.Name;
            string groupName   = jobName + "Group";
            string triggerName = jobName + "Trigger";

            JobBuilder jobBuilder = JobBuilder.Create(type).WithIdentity(jobName, groupName);

            if (jobDataDic != null)
            {
                jobBuilder.UsingJobData(new JobDataMap(jobDataDic));
            }

            IJobDetail job = jobBuilder.Build();

            AddJob(scheduler, intervalTs, startAt, repeatCount, groupName, triggerName, job);
        }
Example #20
0
        public static string create_job(JOB_TYPE type, string group_name, Dictionary <string, object> para = null, string schedule = null)
        {
            if (para == null)
            {
                para = new Dictionary <string, object>()
                {
                }
            }
            ;
            group_name = group_name.ToLower();
            string name = group_name + "." + DateTime.Now.ToString("yyMMdd-HHmmss-fff");

            if (!string.IsNullOrEmpty(schedule))
            {
                name += "." + schedule;
            }

            JobDataMap m = new JobDataMap();

            m.Put("ID___", name);
            m.Put("SCHEDULE___", schedule);
            m.Put("TYPE___", type);
            m.Put("CURRENT_ID___", 0);
            m.Put("COUNTER___", new ConcurrentDictionary <long, bool>());
            m.Put("PARA___", para);

            JobBuilder     job     = null;
            TriggerBuilder trigger = null;

            switch (type)
            {
            case JOB_TYPE.CRAWLER_NET:
            case JOB_TYPE.CRAWLER_CURL:
                job = JobBuilder.Create <JobCrawler>();
                break;

            case JOB_TYPE.API_JS:
                job = JobBuilder.Create <JobApiJS>();
                break;
            }

            if (job != null)
            {
                job     = job.WithIdentity(name, group_name).UsingJobData(m);
                trigger = TriggerBuilder.Create();

                if (!string.IsNullOrEmpty(schedule))
                {
                    trigger = trigger.WithSchedule(CronScheduleBuilder.CronSchedule(schedule));
                }
                trigger = trigger.StartNow();

                var j = job.Build();
                var t = trigger.Build();

                m_scheduler.ScheduleJob(j, t);

                m_job.TryAdd(name, j);
                m_trigger.TryAdd(name, t);

                m_scheduler.ScheduleJob(j, t).Wait();
                return(name);
            }

            return(string.Empty);
        }
Example #21
0
 public void Build()
 {
     JobDetail = JobBuilder.Build();
 }
Example #22
0
        /// <summary>
        /// 添加Job
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static void ScheduleJob(ScheduleJobInput input)
        {
            #region JobDetail
            JobBuilder jobBuilder = JobBuilder
                                    .Create()
                                    .OfType(Type.GetType(input.FullName + "," + input.AssemblyName, true))
                                    .WithDescription(input.JobDescription)
                                    .WithIdentity(new JobKey(input.JobName, input.JobGroup))
                                    .UsingJobData(GetJobDataMap(input));

            if (input.IsRequest)
            {
                //在服务器异常时候,重启调度之后,接着执行调度
                jobBuilder = jobBuilder.RequestRecovery();
            }
            if (input.IsSave)
            {
                //保存到数据库中
                jobBuilder.StoreDurably();
            }
            IJobDetail detail = jobBuilder.Build();
            #endregion

            #region trigger

            var triggerBuilder = TriggerBuilder
                                 .Create()
                                 .ForJob(detail);

            if (!input.ChoicedCalendar.IsNullOrEmpty())
            {
                triggerBuilder.ModifiedByCalendar(input.ChoicedCalendar);
            }
            if (!input.TriggerName.IsNullOrEmpty() && !input.TriggerGroup.IsNullOrEmpty())
            {
                triggerBuilder.WithDescription(input.TriggerDescription)
                .WithIdentity(new TriggerKey(input.TriggerName, input.TriggerGroup));
            }
            #endregion

            //是否替换
            if (input.ReplaceExists)
            {
                var triggers = new global::Quartz.Collection.HashSet <ITrigger>();
                //如果是Cron触发器
                if (input.TriggerType == "CronTriggerImpl")
                {
                    triggers.Add(triggerBuilder.WithCronSchedule(input.Cron).Build());
                }
                else
                {
                    var simpleBuilder = SimpleScheduleBuilder.Create();
                    if (input.Repeat)
                    {
                        simpleBuilder.RepeatForever();
                    }
                    simpleBuilder.WithInterval(input.Interval);
                    triggers.Add(triggerBuilder.WithSchedule(simpleBuilder).Build());
                }
                ScheduleJob(detail, triggers, true);
            }
            else
            {
                //如果是Cron触发器
                if (input.TriggerType == "CronTriggerImpl")
                {
                    ScheduleJob(detail, triggerBuilder.WithCronSchedule(input.Cron).Build());
                }
                else
                {
                    var simpleBuilder = SimpleScheduleBuilder.Create();
                    if (input.Repeat)
                    {
                        simpleBuilder.RepeatForever();
                    }
                    simpleBuilder.WithInterval(input.Interval);
                    ScheduleJob(detail, triggerBuilder.WithSchedule(simpleBuilder).Build());
                }
            }
        }
Example #23
0
        /// <summary>
        /// 添加远程任务
        /// </summary>
        /// <param name="taskid">任务id</param>
        /// <param name="message">返回信息</param>
        /// <returns>是否成功</returns>
        public static bool AddRemoteTask(string taskid,out string message)
        {
            bool result = false;
            try
            {
                TaskBLL td = new TaskBLL();
                var t = td.Detail(taskid);

                TaskRuntimeInfo trun = new TaskRuntimeInfo();
                trun.parms = td.GetParms(taskid);
                switch (t.taskType)
                {
                    case "SQL-FILE":
                        trun.sqlFileTask = new SqlFileTask(t.taskFile, t.taskDBCon);
                        break;
                    case "SQL-EXP":
                        trun.sqlExpTask = new SqlExpJob(t.taskDBCon, t.taskFile, taskid, t.taskParm, trun.parms);
                        break;
                    case "DLL-STD":
                        trun.dllTask = new QMAppDomainLoader<DllTask>().Load(t.taskFile, t.taskClsType, out trun.domain);
                        break;
                    case "DLL-UNSTD":
                    default:
                        trun.unStdDllTask = new UnStdDll(t.taskFile, t.taskParm);
                        break;
                }
                trun.task = t;


                if (!_taskPool.ContainsKey(taskid))
                {
                    //添加任务
                    JobBuilder jobBuilder = JobBuilder.Create()
                                            .WithIdentity(trun.task.idx);
                    //.WithIdentity(taskinfo.task.idx, taskinfo.task.taskCategory);

                    switch (trun.task.taskType)
                    {
                        case "SQL-FILE":
                            jobBuilder = jobBuilder.OfType(typeof(QMSqlFileTaskJob));
                            break;
                        case "SQL-EXP":
                        case "SQL":
                            jobBuilder = jobBuilder.OfType(typeof(QMSqlExpTaskJob));
                            break;
                        case "DLL-STD":
                            jobBuilder = jobBuilder.OfType(typeof(QMDllTaskJob));
                            break;
                        case "DLL-UNSTD":
                        default:
                            jobBuilder = jobBuilder.OfType(typeof(QMUnStdDllTaskJob));
                            break;
                    }

                    IJobDetail jobDetail = jobBuilder.Build();

                    //任务Misfire处理规则
                    //以当前时间为触发频率立刻触发一次执行
                    //然后按照Cron频率依次执行        
                    ITrigger trigger = TriggerBuilder.Create()
                                    .WithIdentity(trun.task.taskName, "Cron")
                                    .WithCronSchedule(trun.task.taskCron,
                                        x => x.WithMisfireHandlingInstructionFireAndProceed())
                                    .ForJob(jobDetail.Key)
                                    .Build();                       


                    if (_remoteScheduler.CheckExists(jobDetail.Key).Result)
                    {
                        _remoteScheduler.DeleteJob(jobDetail.Key);
                    }
                    _remoteScheduler.ScheduleJob(jobDetail, trigger);

                    _taskPool.Add(taskid, trun);
                }
                

                message = string.Format("添加远程任务成功:{0}", taskid);
                result = true;
            }
            catch (QMException ex)
            {
                message = string.Format("添加远程任务失败:{0},{1}", ex.Message, ex.StackTrace);
                log.Fatal(message);                
            }

            return result;
        }
Example #24
0
        /// <summary>
        /// 添加任务到队列中
        /// </summary>
        /// <param name="taskid"></param>
        /// <param name="taskinfo"></param>
        /// <param name="misfire"></param>
        /// <returns></returns>
        public static async Task<bool> AddTask(string taskid, TaskRuntimeInfo taskinfo, QMMisFire misfire = QMMisFire.DoNothing) 
        {
            if (!_taskPool.ContainsKey(taskid))
            {
                //添加任务
                JobBuilder jobBuilder = JobBuilder.Create()
                                        .WithIdentity(taskinfo.task.idx);
                                        //.WithIdentity(taskinfo.task.idx, taskinfo.task.taskCategory);

                switch (taskinfo.task.taskType) {
                    case "SQL-FILE":
                        jobBuilder = jobBuilder.OfType(typeof(QMSqlFileTaskJob));
                        break;
                    case "SQL-EXP":
                    case "SQL":
                        jobBuilder = jobBuilder.OfType(typeof(QMSqlExpTaskJob));
                        break;
                    case "DLL-STD":
                        jobBuilder = jobBuilder.OfType(typeof(QMDllTaskJob));
                        break;
                    case "DLL-UNSTD":
                    default:
                        jobBuilder = jobBuilder.OfType(typeof(QMUnStdDllTaskJob));
                        break;
                }

                IJobDetail jobDetail = jobBuilder.Build();

                //任务Misfire处理规则
                ITrigger trigger;
                    
                if (misfire == QMMisFire.FireAndProceed)        
                {
                    //以当前时间为触发频率立刻触发一次执行
                    //然后按照Cron频率依次执行        
                    trigger = TriggerBuilder.Create()
                                    .WithIdentity(taskinfo.task.taskName, "Cron")
                                    .WithCronSchedule(taskinfo.task.taskCron,
                                        x => x.WithMisfireHandlingInstructionFireAndProceed())
                                    .ForJob(jobDetail.Key)
                                    .Build();
                }
                else if (misfire == QMMisFire.IgnoreMisfires)       
                {
                    //以错过的第一个频率时间立刻开始执行
                    //重做错过的所有频率周期后
                    //当下一次触发频率发生时间大于当前时间后,再按照正常的Cron频率依次执行
                    trigger = TriggerBuilder.Create()
                                            .WithIdentity(taskinfo.task.taskName, "Cron")
                                            .WithCronSchedule(taskinfo.task.taskCron,
                                                x => x.WithMisfireHandlingInstructionIgnoreMisfires())
                                            .ForJob(jobDetail.Key)
                                            .Build();
                }
                else
                {
                    //不触发立即执行
                    //等待下次Cron触发频率到达时刻开始按照Cron频率依次执行
                    trigger = TriggerBuilder.Create()
                    .WithIdentity(taskinfo.task.taskName, "Cron")
                    .WithCronSchedule(taskinfo.task.taskCron,
                        x => x.WithMisfireHandlingInstructionDoNothing())
                    .ForJob(jobDetail.Key)
                    .Build();
                }


                if (!await _scheduler.CheckExists(jobDetail.Key))
                {
                    //await _scheduler.DeleteJob(jobDetail.Key);
                    await _scheduler.ScheduleJob(jobDetail, trigger);
                }                                                                              
                    
                _taskPool.Add(taskid, taskinfo);
                return true;
            }

            return false;            
        }
Example #25
0
 private void ScheduleJob(JobBuilder job, TriggerBuilder trigger)
 {
     _sched.ScheduleJob(job.Build(), trigger.Build());
 }