QuartzHostedService 是一个用来在Asp.Net Core 中实现 Quartz 的任务注入依赖的nuget 包:
基本示例如下:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using AspNetCoreSampleQuartzHostedService.Jobs;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Options;using Quartz;using QuartzHostedService;namespace AspNetCoreSampleQuartzHostedService{ 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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddOptions(); services.Configure(Configuration); services.Configure (options => { options.WriteText = "This is inject string"; }); services.AddQuartzHostedService() .AddQuartzJob () .AddQuartzJob () .AddQuartzJob () .AddQuartzJob (); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions settings) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); if (settings.Value.EnableHelloSingleJob) { app.UseQuartzJob (TriggerBuilder.Create().WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever())) .UseQuartzJob (() => { return TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever()); }); } if (settings.Value.EnableHelloJob) { app.UseQuartzJob (new List { TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever()), TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever()) }); app.UseQuartzJob (() => { var result = new List (); result.Add(TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())); return result; }); } } }}
扩展方式示例:
public static class ModBusScheduler { public static void AddQuartzJobsService(this IServiceCollection services) { services.AddQuartzHostedService() .AddQuartzJob("HAVC_Elev") .AddQuartzJob ("Lighting", "Lighting") .AddQuartzJobDetail(() => JobBuilder.Create ().WithIdentity("Meter").Build()) .AddQuartzJobDetail(() => JobBuilder.Create ().WithIdentity("PowerDis").Build()); } public static void UserQuartzJobsService(this IApplicationBuilder app, AppSettings settings) { app.UseQuartzJob ("HAVC_Elev", () => { return TriggerBuilder.Create() .WithIdentity("HAVC_Elev") .UsingJobData("modbus", settings.AC_ElevatorSlave) .UsingJobData("devicetype", "HAVC_Elev") .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()).StartNow(); });}
nuget 连接
github地址 https://github.com/mukmyash/QuartzHostedService