SACenter/SA.Quartz/QuartzStartup.cs

75 lines
2.8 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using System.Linq;
namespace SA.Quartz
{
using IOCContainer = IServiceProvider;
// Quartz.Net启动后注册job和trigger
public class QuartzStartup
{
private IScheduler Scheduler { get; set; }
private readonly IJobFactory iocJobfactory;
public QuartzStartup(IOCContainer IocContainer)
{
iocJobfactory = new IOCJobFactory(IocContainer);
var schedulerFactory = new StdSchedulerFactory();
Scheduler = schedulerFactory.GetScheduler().Result;
Scheduler.JobFactory = iocJobfactory;
}
public void Start()
{
Log.Information("Schedule job load as application start.");
Scheduler.Start().Wait();
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IJob))))
.ToArray();
var jobCount = 0;
foreach (var type in types)
{
foreach (QuartzJobAttribute quartzJob in type.GetCustomAttributes(typeof(QuartzJobAttribute), true))
{
var jobDetail = JobBuilder.Create(type)
.WithIdentity(quartzJob.Name, quartzJob.Group)
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity(quartzJob.Name, quartzJob.Group)
// Seconds,Minutes,HoursDay-of-MonthMonthDay-of-WeekYearoptional field
.If(quartzJob.Action != null, x => x.WithSimpleSchedule(quartzJob.Action))
.If(!string.IsNullOrEmpty(quartzJob.Cron), x => x.WithCronSchedule(quartzJob.Cron))
.StartNow();
foreach (QuartzDataAttribute quartzData in type.GetCustomAttributes(typeof(QuartzDataAttribute), true))
{
trigger.AddJobData(quartzData.Key, quartzData.Value, quartzData.ValueType);
}
jobCount++;
Scheduler.ScheduleJob(jobDetail, trigger.Build()).Wait();
Scheduler.TriggerJob(new JobKey(quartzJob.Name, quartzJob.Group));
}
}
Log.Information($"{jobCount} quartz jobs were successfully initialized. Schedule job load end.");
}
public void Stop()
{
if (Scheduler == null)
{
return;
}
if (Scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
Scheduler = null;
else
{
}
Log.Warning("Schedule job upload as application stopped.");
}
}
}