using System; using System.Linq; using System.Threading.Tasks; using HHWMS.Web.Models; using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Impl; using Quartz.Impl.Triggers; using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Core.Support.Quartz; namespace HHWMS.Web.Support { public class QuartzService { private readonly IServiceProvider _sp; private readonly GlobalData _gd; private readonly IDataContext _context; private IScheduler _scheduler; private static Task task_scheduler = StdSchedulerFactory.GetDefaultScheduler(); private static readonly object objlock = new object(); //public static DevCommuBySocketClient wcsCommuBySocketClient = new DevCommuBySocketClient("192.168.10.235", 3333, 1000); public QuartzService(IServiceProvider sp, GlobalData gd, IDataContext context) { _sp = sp; _gd = gd; _context = context; if (_scheduler == null) { lock (objlock) { if (_scheduler == null) { _scheduler = task_scheduler.Result; if (!_scheduler.IsStarted) _scheduler.Start(); } } } } public async Task AddJob(SysJob jobDetail) { try { var test = _gd.AllAssembly.FirstOrDefault(x => x.FullName.Contains("HHWMS.Web")); if (test == null) { // 程序集未加载:记录日志并跳过,避免启动流程中断 WriteJobError($"启动任务 {jobDetail.JobName} 失败:未找到 HHWMS.Web 程序集"); return; } var t = test.GetExportedTypes().FirstOrDefault(x => typeof(WtmJob).IsAssignableFrom(x) && x.Name == jobDetail.JobName); if (t == null) { // 类名不匹配:列出可用类型,便于排查数据库 SysJob 表中的无效记录 var available = string.Join(", ", test.GetExportedTypes() .Where(x => typeof(WtmJob).IsAssignableFrom(x)) .Select(x => x.Name)); WriteJobError($"启动任务 {jobDetail.JobName} 失败:未找到对应类型,可用类型:{available}"); return; } var ci = t.GetConstructor(Type.EmptyTypes); if (ci == null) { WriteJobError($"启动任务 {jobDetail.JobName} 失败:类型 {t.FullName} 缺少无参构造函数"); return; } if (ci.Invoke(null) as WtmJob != null) { string jobName = jobDetail.JobName; string groupName = jobDetail.JobName; if (await _scheduler.CheckExists(new JobKey(jobName, groupName))) { ModJob(jobDetail); return; } JobDataMap jobDataMap = new JobDataMap(); jobDataMap.Add("Sp", _sp); // 创建作业 IJobDetail j = JobBuilder.Create(t) .WithIdentity(jobName, groupName) .UsingJobData(jobDataMap) .Build(); // 创建触发器 ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity(jobName, groupName) .WithCronSchedule(jobDetail.CronExpression) .ForJob(new JobKey(jobName, groupName)) .Build(); ((CronTriggerImpl)trigger).MisfireInstruction = MisfireInstruction.CronTrigger.DoNothing; await _scheduler.ScheduleJob(j, trigger); if (jobDetail.Status == SysJobEnum.stoped) _scheduler.PauseJob(new JobKey(jobName, groupName)).Wait(); } } catch (Exception ex) { // 记录启动任务的异常信息,避免被静默吞掉导致难以排查 WriteJobError($"启动任务 {jobDetail.JobName} 异常:{ex.Message}"); } } /// /// 将启动任务的错误信息写入系统日志(ActionLogs),便于排查任务配置问题 /// /// 错误信息 private void WriteJobError(string message) { try { // WTMContext 是 Scoped 服务,不能从 root provider 直接解析,需创建独立作用域 var scopeFactory = _sp.GetService(typeof(IServiceScopeFactory)) as IServiceScopeFactory; if (scopeFactory == null) { return; } using (var scope = scopeFactory.CreateScope()) { var wtm = scope.ServiceProvider.GetService(typeof(WTMContext)) as WTMContext; wtm?.DoLog("", ActionLogTypesEnum.Normal, "QuartzService", result: message); } } catch { // 写日志失败不影响主流程 } } public void DeleteJob(SysJob job) { _scheduler.PauseTrigger(new TriggerKey(job.JobName, job.JobGroup)).Wait(); _scheduler.UnscheduleJob(new TriggerKey(job.JobName, job.JobGroup)).Wait(); _scheduler.DeleteJob(new JobKey(job.JobName, job.JobGroup)).Wait(); } public void Execute(SysJob job) { _scheduler.TriggerJob(new JobKey(job.JobName, job.JobGroup)).Wait(); } public void ModJob(SysJob job) { TriggerKey triggerKey = new TriggerKey(job.JobName, job.JobGroup); ITrigger trigger = _scheduler.GetTrigger(triggerKey).Result; CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.CronSchedule(job.CronExpression); trigger = trigger.GetTriggerBuilder() .WithIdentity(triggerKey) .WithSchedule(scheduleBuilder.WithMisfireHandlingInstructionDoNothing()) .Build(); _scheduler.RescheduleJob(triggerKey, trigger).Wait(); if (job.Status == SysJobEnum.stoped) _scheduler.PauseJob(new JobKey(job.JobName, job.JobGroup)); } } }