.Net Core使用xxl-job定时任务
一、下载NuGet包
NuGet:DotXxlJob.Core
二、Startup类
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) { services.AddControllers(); // 注入xxl-job services.AddxxlJobs(Configuration); } // 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(); } // 注入xxl-job执行器 app.UseXxlJobExecutor(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
二、appsettings.json配置文件
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "xxlJob": { "adminAddresses": "http://192.168.140.130:8080/xxl-job-admin", //调度服务平台的地址 "appName": "xxl-job-dotnet", //执行器的名称,与调度平台配置的名称必须一致 "specialBindAddress": "192.168.0.102", //被调度的服务地址 "port": 5003, //被调度的服务端口 "autoRegistry": true, "accessToken": "", "logRetentionDays": 30, "logPath ": "/LogFile" } }
三、DependencyInjectionExtersion类
public static class DependencyInjectionExtersion { public static IServiceCollection AddxxlJobs(this IServiceCollection services, IConfiguration configurationSection) { services.AddXxlJobExecutor(configurationSection); var types = GetSubClassType(typeof(AbstractJobHandler)); var methods = typeof(ServiceCollectionServiceExtensions).GetMethods(); MethodInfo method = methods.FirstOrDefault(m => m.Name == "AddSingleton" && m.IsGenericMethod && m.GetGenericArguments().Length == 2); // 自动注册Job,请勿手动注册 foreach (var type in types) { var registerMethod = method.MakeGenericMethod(new Type[] { typeof(IJobHandler), type }); registerMethod.Invoke(services, new object[] { services }); } services.AddAutoRegistry(); return services; } public static List<Type> GetSubClassType(Type baseType) { var allTypes = typeof(DemoHandler).Assembly.GetTypes(); return allTypes.Where(t => t.BaseType != null && t.BaseType.Equals(baseType)).ToList(); } public static IApplicationBuilder UseXxlJobExecutor(this IApplicationBuilder builder) { return builder.UseMiddleware<XxlJobExecutorMiddleware>(); } }
四、XxlJobExecutorMiddleware类
public class XxlJobExecutorMiddleware { private readonly IServiceProvider _provider; private readonly RequestDelegate _next; private readonly ILogger _logger; private readonly XxlRestfulServiceHandler _rpcService; public XxlJobExecutorMiddleware(IServiceProvider provider, RequestDelegate next, ILoggerFactory loggerFactory) { this._provider = provider; this._next = next; this._rpcService = _provider.GetRequiredService<XxlRestfulServiceHandler>(); _logger = loggerFactory.CreateLogger(this.GetType()); } public async Task Invoke(HttpContext context) { string contentType = context.Request.ContentType; if ("POST".Equals(context.Request.Method, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(contentType) && contentType.ToLower().StartsWith("application/json")) { await _rpcService.HandlerAsync(context.Request, context.Response); return; } await _next.Invoke(context); } }
五、DemoHandler
[JobHandler("DemoHandler")] public class DemoHandler: AbstractJobHandler { public async override Task<ReturnT> Execute(JobExecuteContext context) { // dosomething { // 获取xxl-job传参(根据业务需求,也可不设置参数) var jobParameter = context.JobParameter.GetParameter(); if (jobParameter!=null && !string.IsNullOrWhiteSpace(jobParameter.UserName)) { // dosomething } } return await Task.FromResult(ReturnT.SUCCESS); } }
六、JobParameterConvert
public static class JobParameterConvert { public static JobParameter GetParameter(this string paramString) { if (string.IsNullOrEmpty(paramString)) return new JobParameter(); return JsonConvert.DeserializeObject<JobParameter>(paramString); } } public class JobParameter { public string UserName { get; set; } }
七、xxl-job服务端配置执行器
八、xxl-job服务端配置任务
查看任务执行日志
GitHub:https://github.com/NanoFabricFX/DotXxlJob/tree/master/samples/ASPNetCoreExecutor