Exemplo n.º 1
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);
    }
Exemplo n.º 2
0
        /// <summary>
        /// 调度任务
        /// </summary>
        /// <typeparam name="T">任务类型</typeparam>
        /// <param name="delay">延迟时间(毫秒)</param>
        /// <remarks>适用于没有参数,只有策略的任务</remarks>
        public static void Schedule <T>(int delay = 1000) where T : class, ICrontab
        {
            //调度任务
            Type crontabType = typeof(T);

            #region # 验证

            if (!CrontabSetting.CrontabStrategies.ContainsKey(crontabType.Name))
            {
                throw new InvalidOperationException($"没有为定时任务\"{crontabType.Name}\"配置执行策略");
            }

            #endregion

            ExecutionStrategy executionStrategy = CrontabSetting.CrontabStrategies[crontabType.Name];
            ICrontab          crontab           = CrontabFactory.CreateCrontab(crontabType, executionStrategy);

            IEnumerable <ICrontabExecutor> crontabExecutors = CrontabExecutorFactory.GetCrontabExecutorsFor(crontabType);
            foreach (ICrontabExecutor crontabExecutor in crontabExecutors)
            {
                JobKey jobKey = new JobKey(crontab.Id);
                if (!_Scheduler.CheckExists(jobKey).Result)
                {
                    Type       jobType    = crontabExecutor.GetType();
                    JobBuilder jobBuilder = JobBuilder.Create(jobType);

                    //设置任务数据
                    IDictionary <string, object> dictionary = new Dictionary <string, object>();
                    dictionary.Add(crontab.Id, crontab);
                    jobBuilder.SetJobData(new JobDataMap(dictionary));

                    //创建任务明细
                    IJobDetail jobDetail = jobBuilder.WithIdentity(jobKey).Build();

                    //创建触发器
                    ITrigger trigger = GetTrigger(crontab.ExecutionStrategy);

                    //为调度者添加任务明细与触发器
                    _Scheduler.ScheduleJob(jobDetail, trigger).Wait();

                    //开始调度
                    _Scheduler.StartDelayed(TimeSpan.FromMilliseconds(delay)).Wait();
                }
                else
                {
                    _Scheduler.ResumeJob(jobKey).Wait();
                }
            }

            //保存任务
            using (ICrontabStore crontabStore = ResolveMediator.ResolveOptional <ICrontabStore>())
            {
                crontab.Status = CrontabStatus.Scheduled;
                crontabStore?.Store(crontab);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 调度任务
        /// </summary>
        /// <param name="crontab">定时任务</param>
        public static void Schedule(ICrontab crontab)
        {
            #region # 验证

            if (crontab.ExecutionStrategy == null)
            {
                throw new InvalidOperationException("执行策略不可为空!");
            }

            #endregion

            //调度任务
            Type crontabType = crontab.GetType();
            IEnumerable <ICrontabExecutor> crontabSchedulers = CrontabExecutorFactory.GetCrontabExecutorsFor(crontabType);
            foreach (ICrontabExecutor scheduler in crontabSchedulers)
            {
                JobKey jobKey = new JobKey(crontab.Id);

                if (!_Scheduler.CheckExists(jobKey).Result)
                {
                    Type       jobType    = scheduler.GetType();
                    JobBuilder jobBuilder = JobBuilder.Create(jobType);

                    //设置任务数据
                    IDictionary <string, object> dictionary = new Dictionary <string, object>();
                    dictionary.Add(crontab.Id, crontab);
                    jobBuilder.SetJobData(new JobDataMap(dictionary));

                    //创建任务明细
                    IJobDetail jobDetail = jobBuilder.WithIdentity(jobKey).Build();

                    //创建触发器
                    ITrigger trigger = GetTrigger(crontab.ExecutionStrategy);

                    //为调度者添加任务明细与触发器
                    _Scheduler.ScheduleJob(jobDetail, trigger).Wait();

                    //开始调度
                    _Scheduler.Start().Wait();
                }
                else
                {
                    _Scheduler.ResumeJob(jobKey).Wait();
                }
            }

            //保存任务
            using (ICrontabStore crontabStore = ResolveMediator.ResolveOptional <ICrontabStore>())
            {
                crontab.Status = CrontabStatus.Scheduled;
                crontabStore?.Store(crontab);
            }
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
 public void ConfigureJob(JobBuilder job)
 {
     job.WithIdentity("美食天下", "菜谱Img")
     .WithDescription("美食天下");
 }
Exemplo n.º 6
0
        public void AddJob(JobInfo jobInfo)
        {
            if (string.IsNullOrEmpty(jobInfo.JobName) || string.IsNullOrEmpty(jobInfo.GroupName))
            {
                throw new Exception("job名称与组名都不能为空");
            }

            if (jobInfo.StartTime < new DateTime(1900, 1, 1))
            {
                throw new Exception("开始时间不正确");
            }

            if (string.IsNullOrEmpty(jobInfo.FileName) || string.IsNullOrEmpty(jobInfo.ClassName))
            {
                throw new Exception("程序集地址和类名都不能为空");
            }

            // 反射获取job实例
            Assembly assembly = Consts.GetAssembly(jobInfo.FileName);
            BaseJob  job      = assembly.CreateInstance(jobInfo.ClassName) as BaseJob;

            if (job == null)
            {
                throw new Exception("无法实例化job类");
            }

            JobBuilder jobBuilder = null;

            if (jobInfo.CanConcurrent)
            {
                jobBuilder = JobBuilder.Create <HostJob>();              // 可以多线程
            }
            else
            {
                jobBuilder = JobBuilder.Create <HostJob>();        // 不能多线程
            }

            IJobDetail innerJob = jobBuilder
                                  .WithIdentity(jobInfo.JobName, jobInfo.GroupName)
                                  .UsingJobData(Consts.JobParameter, jobInfo.Parameter)
                                  .UsingJobData(Consts.JobAssemblyPath, jobInfo.FileName)
                                  .UsingJobData(Consts.JobClassName, jobInfo.ClassName)
                                  .RequestRecovery(true)
                                  .Build();

            TriggerBuilder builder = TriggerBuilder.Create().WithIdentity(jobInfo.JobName, jobInfo.GroupName);

            if (jobInfo.RepeatMode == RepeatModeEnum.Interval)
            {
                if (jobInfo.Interval <= 0)
                {
                    throw new Exception("时间间隔必须大于0");
                }

                switch (jobInfo.CycleUnit)
                {
                case CycleUnitEnum.Day:
                    builder = builder.WithSimpleSchedule(x => x.WithIntervalInHours(24 * jobInfo.Interval).RepeatForever().WithMisfireHandlingInstructionIgnoreMisfires());
                    break;

                case CycleUnitEnum.Hour:
                    builder = builder.WithSimpleSchedule(x => x.WithIntervalInHours(jobInfo.Interval).RepeatForever().WithMisfireHandlingInstructionIgnoreMisfires());
                    break;

                case CycleUnitEnum.Minute:
                    builder = builder.WithSimpleSchedule(x => x.WithIntervalInMinutes(jobInfo.Interval).RepeatForever().WithMisfireHandlingInstructionIgnoreMisfires());
                    break;

                case CycleUnitEnum.Second:
                    builder = builder.WithSimpleSchedule(x => x.WithIntervalInSeconds(jobInfo.Interval).RepeatForever().WithMisfireHandlingInstructionIgnoreMisfires());
                    break;
                }
            }
            else if (jobInfo.RepeatMode == RepeatModeEnum.FixedTime)
            {
                if (string.IsNullOrEmpty(jobInfo.FixedExpression))
                {
                    throw new Exception("Job按固定时间配置时,固定时间的表达式不能为空");
                }

                var expression = string.Empty;
                var fixedExs   = jobInfo.FixedExpression.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var localParts = fixedExs[0].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

                switch (jobInfo.FixedUnit)
                {
                case FixedUnitEnum.Day:
                    var localMinute   = Convert.ToInt32(localParts[1]);
                    var localSecond   = Convert.ToInt32(localParts[2]);
                    var localHourList = new List <int>();
                    foreach (var item in fixedExs)
                    {
                        localParts = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        localHourList.Add(Convert.ToInt32(localParts[0]));
                    }
                    var localHours = string.Join(",", localHourList);
                    expression = string.Format("{0} {1} {2} * * ?", localSecond, localMinute, localHours);

                    break;

                case FixedUnitEnum.Hour:
                    localSecond = Convert.ToInt32(localParts[1]);
                    var localMinuteList = new List <int>();
                    foreach (var item in fixedExs)
                    {
                        localParts = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        localMinuteList.Add(Convert.ToInt32(localParts[0]));
                    }
                    var localMinutes = string.Join(",", localMinuteList);
                    expression = string.Format("{0} {1} * * * ?", localSecond, localMinutes);

                    break;
                }

                builder = builder.WithCronSchedule(expression,
                                                   x => x.WithMisfireHandlingInstructionIgnoreMisfires().InTimeZone(TimeZoneInfo.Local));
            }
            else if (jobInfo.RepeatMode == RepeatModeEnum.CronExp)
            {
                builder = builder.WithCronSchedule(jobInfo.FixedExpression,
                                                   x => x.WithMisfireHandlingInstructionIgnoreMisfires().InTimeZone(TimeZoneInfo.Local));
            }

            if (jobInfo.StartTime < DateTime.Now.AddMinutes(1))
            {
                jobInfo.StartTime = DateTime.Now.AddMinutes(1);
            }
            builder.StartAt(jobInfo.StartTime);
            ITrigger trigger = builder.Build();

            HostScheduler.RegisterJob(innerJob, trigger);
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
 public void ConfigureJob(JobBuilder job)
 {
     job.WithIdentity("苏州菜价行情", "菜价行情")
     .WithDescription("苏州价格在线");
 }