using System;
using System.Collections.Specialized;
using System.Data;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Logging;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.AdoJobStore.Common;
using Quartz.Spi;namespace EqidManager
{using IOCContainer = IServiceProvider;public class QuartzStartup{public IScheduler Scheduler { get; set; }private readonly ILogger _logger;private readonly IJobFactory iocJobfactory;public QuartzStartup(IOCContainer IocContainer, ILoggerFactory loggerFactory){_logger = loggerFactory.CreateLogger<QuartzStartup>();iocJobfactory = new IOCJobFactory(IocContainer);DbProvider.RegisterDbMetadata("sqlite-custom", new DbMetadata(){AssemblyName = typeof(SqliteConnection).Assembly.GetName().Name,ConnectionType = typeof(SqliteConnection),CommandType = typeof(SqliteCommand),ParameterType = typeof(SqliteParameter),ParameterDbType = typeof(DbType),ParameterDbTypePropertyName = "DbType",ParameterNamePrefix = "@",ExceptionType = typeof(SqliteException),BindByName = true});var properties = new NameValueCollection{["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz",["quartz.jobStore.useProperties"] = "true",["quartz.jobStore.dataSource"] = "default",["quartz.jobStore.tablePrefix"] = "QRTZ_",["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SQLiteDelegate, Quartz",["quartz.dataSource.default.provider"] = "sqlite-custom",["quartz.dataSource.default.connectionString"] = "Data Source=EqidManager.db",["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz",["quartz.serializer.type"] = "binary"};var schedulerFactory = new StdSchedulerFactory(properties);Scheduler = schedulerFactory.GetScheduler().Result;Scheduler.JobFactory = iocJobfactory;}public async Task<IScheduler> ScheduleJob(){var _eqidCounterResetJob = JobBuilder.Create<EqidCounterResetJob>().WithIdentity("EqidCounterResetJob").Build();var _eqidCounterResetJobTrigger = TriggerBuilder.Create().WithIdentity("EqidCounterResetCron").StartNow()//每天凌晨0s.WithCronSchedule("0 0 0 * * ?") Seconds,Minutes,Hours,Day-of-Month,Month,Day-of-Week,Year(optional field).Build();// 這里一定要先判斷是否已經(jīng)從SQlite中加載了Job和Triggerif (!await Scheduler.CheckExists(new JobKey("EqidCounterResetJob")) &&!await Scheduler.CheckExists(new TriggerKey("EqidCounterResetCron"))){await Scheduler.ScheduleJob(_eqidCounterResetJob, _eqidCounterResetJobTrigger);}await Scheduler.Start();return Scheduler;}public void EndScheduler(){if (Scheduler == null){return;}if (Scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))Scheduler = null;else{}_logger.LogError("Schedule job upload as application stopped");}}
}
上面是Quartz.NET 從sqlite中加載Job和Trigger的核心代碼
這里要提示兩點(diǎn):
①??IOCJobFactory 是自定義JobFactory,目的是與ASP.NET Core原生依賴注入結(jié)合 ② 在調(diào)度任務(wù)的時(shí)候,先判斷是否已經(jīng)從sqlite加載了Job和Trigger
3.添加Quartz.Net UI輪子
附贈(zèng)Quartz.NET的調(diào)度UI: CrystalQuartz, 方便在界面管理和調(diào)度任務(wù) ① Install-Package CrystalQuartz.AspNetCore -IncludePrerelease ② Startup啟用CrystalQuartz
using CrystalQuartz.AspNetCore;
/** app is IAppBuilder* scheduler is your IScheduler (local or remote)*/
var quartz = app.ApplicationServices.GetRequiredService<QuartzStartup>();
var _schedule = await quartz.ScheduleJob();
app.UseCrystalQuartz(() => scheduler);