Example #1
0
        private IServiceProvider GetServiceProvider()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddHttpClient();

            services.AddCore();

            services.AddTransient <JobFactory>();
            services.AddTransient <JobService>();
            services.AddTransient <JobListener>();
            services.AddTransient <BaseJob>();


            FileQuartz.CreateQuartzRootPath();
            IServiceProvider serviceProvider = services.BuildServiceProvider();

            return(serviceProvider);
        }
        /// <summary>
        /// 初始化作业
        /// </summary>
        /// <param name="applicationBuilder"></param>
        /// <param name="env"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseQuartz(this IApplicationBuilder applicationBuilder, IHostingEnvironment env)
        {
            IServiceProvider services = applicationBuilder.ApplicationServices;

            ISchedulerFactory _schedulerFactory = services.GetService <ISchedulerFactory>();

            string path      = FileQuartz.CreateQuartzRootPath(env);
            string jobConfig = FileHelper.ReadFile(path + QuartzFileInfo.JobConfigFileName);

            if (string.IsNullOrEmpty(jobConfig))
            {
                FileHelper.WriteFile(FileQuartz.LogPath, "start.txt", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},没有默认配置任务\r\n", true);
                return(applicationBuilder);
            }

            int         errorCount = 0;
            string      errorMsg   = "";
            TaskOptions options    = null;

            try
            {
                //TODO:从数据库获取任务列表
                _taskList = JsonConvert.DeserializeObject <List <TaskOptions> >(jobConfig);
                _taskList.ForEach(x =>
                {
                    options    = x;
                    var result = x.AddJob(_schedulerFactory, true).Result;
                });
            }
            catch (Exception ex)
            {
                errorCount = +1;
                errorMsg  += $"作业:{options?.TaskName},异常:{ex.Message}";
            }
            string content = $"成功:{   _taskList.Count - errorCount}个,失败{errorCount}个,异常:{errorMsg}\r\n";

            FileQuartz.WriteStartLog(content);


            return(applicationBuilder);
        }