asp.net core webapi中quartz.net基础使用。

1.安装依赖的包。

 

2.新建hostedservice类,实现IHostedService接口

using Microsoft.Extensions.Hosting;
using Quartz;
using quartz_webapi.Jobs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace quartz_webapi
{
    public class JobHostedService: IHostedService
    {
        private readonly ISchedulerFactory _schedulerFactory;
        
        private readonly IEnumerable<JobSchedule> _jobSchedules;

        public JobHostedService(ISchedulerFactory schedulerFactory, IEnumerable<JobSchedule> jobSchedules)
        {
            this._schedulerFactory = schedulerFactory;
            this._jobSchedules = jobSchedules;
        }

        public IScheduler _scheduler { get; set; }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
            foreach(var item in _jobSchedules)
            {
                var job = CreateJob(item);
                var trigger = CreateTrigger(item);
                await _scheduler.ScheduleJob(job, trigger, cancellationToken);
            }
            await _scheduler.Start(cancellationToken);
        }
         

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _scheduler.Shutdown(cancellationToken); 
        }
        private static IJobDetail CreateJob(JobSchedule schedule)
        {
            Type jobType = schedule.JobType;
            return JobBuilder.Create(jobType).WithIdentity(jobType.FullName).WithDescription(jobType.Name)
                .Build();
        }

        private static ITrigger CreateTrigger(JobSchedule schedule)
        {
            return TriggerBuilder.Create().WithIdentity(schedule.JobType.FullName + ".trigger").WithCronSchedule(schedule.CronExpression)
                .WithDescription(schedule.CronExpression)
                .Build();
        }
    }
    public class JobSchedule
    {
        public Type JobType { get; private set; }

        public string CronExpression { get; private set; }



        public JobSchedule(Type jobType, string cronExpression)
        {
            JobType = jobType ?? throw new ArgumentNullException("jobType");
            CronExpression = cronExpression ?? throw new ArgumentNullException("cronExpression");
        }
    }
}

由于我本地的项目同时有多个job在运行,所以这里是通过读配置文件反射出来的jobdetail。

3.在setup.cs类中加载相关的类。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;
using quartz_webapi.Jobs;
using System;

namespace quartz_webapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            AppCache.Connection = Configuration.GetSection("ConnectionConfigs").Get<ConnectionConfigs>();
            AppCache.JobSettings = Configuration.GetSection("JobSettings").Get<JobSettings>();
              
            services.AddControllers();
            services.AddSingleton<ISchedulerFactory,StdSchedulerFactory>();
            if (AppCache.JobSettings == null)
            {
                throw new Exception("请先正确配置appsettings.josn中的jobsettings节点。");
            }
            foreach (TaskScheduler item in AppCache.JobSettings.TaskSchedulers)
            {
                if (item.Enable && item.Code.Equals("InpBillDetailJob"))
                {
                    services.AddSingleton<InpBillDetailJob>(); 
                    services.AddSingleton(new JobSchedule(typeof(InpBillDetailJob), item.CronExpression));
                }
                
                else if (item.Enable && item.Code.Equals("myjob22"))
                { 
                    services.AddSingleton<MyJob2>();
                    services.AddSingleton(new JobSchedule(typeof(MyJob2), item.CronExpression));
                }
            }
            services.AddHostedService<JobHostedService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
using Quartz;
using quartz_webapi.Jobs_execute;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace quartz_webapi.Jobs
{
    public class InpBillDetailJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() =>
            {
                new InpBillDetailJob_execute().Run("1111", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            });
        }
    }
}
using System;
using System.Collections.Generic;
using System.Data;
using quartz_webapi.Entitys;
using quartz_webapi.Utils;

namespace quartz_webapi.Jobs_execute
{
    public class InpBillDetailJob_execute
    {
        public JsonResponse Run(string name,string datetime)
        {
            return new JsonResponse
            {
                State = true,
                Message = "执行结束."
            };
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace quartz_webapi
{
    public class JsonResponse
    {
        public bool State { get; set; }

        public string Message { get; set; }
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  //数据库连接配置
  "ConnectionConfigs": {
    "ConnId": "1",
    "ConnType": "ORACLE",
    "ConnDescription": "业务库",
    "ConnectionString": "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(sid = test)));User Id=system;Password=manager;"
  },
  //定时任务设置
  "JobSettings": {
    "TaskSchedulers": [
      {
        "Code": "InpBillDetailJob",
        "Memo": "",
        "Enable": true,
        "CronExpression": "0 18 17 * * ?"
      }
    ]
  }
}

 

posted @ 2022-08-11 17:46  沙漠之鹰NO1  阅读(645)  评论(0编辑  收藏  举报