MasstransferExporter/MasstransferCommon/Scheduler/SchedulerHelper.cs

98 lines
3.0 KiB
C#

using Quartz;
using Quartz.Impl;
using Serilog;
namespace MasstransferCommon.scheduler;
public class SchedulerHelper
{
private static readonly Lazy<IScheduler> lazyScheduler = new(() => InitSchedulerAsync().GetAwaiter().GetResult());
private static readonly Dictionary<string, IJobDetail> _jobDetails = new();
private static IScheduler Scheduler => lazyScheduler.Value;
private static async Task<IScheduler> InitSchedulerAsync()
{
try
{
return await new StdSchedulerFactory().GetScheduler();
}
catch (Exception ex)
{
Log.Error($"Failed to initialize scheduler: {ex.Message}");
throw;
}
}
public static async Task Start()
{
await Scheduler.Start();
}
public static async Task SchedulerInterval<T>(Dictionary<string, object>? data, int interval,
string group = "defaultGroup") where T : IJob
{
var job = CreateJob<T>(data, group);
var trigger = TriggerBuilder.Create()
.WithIdentity(typeof(T).Name, group)
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(interval).RepeatForever())
.Build();
await Scheduler.ScheduleJob(job, trigger);
}
public static async Task SchedulerCorn<T>(Dictionary<string, object>? data, string? cronExpression,
string group = "defaultGroup") where T : IJob
{
var job = CreateJob<T>(data, group);
var trigger = TriggerBuilder.Create()
.WithIdentity(typeof(T).Name, group)
.StartNow()
.WithSchedule(CronScheduleBuilder.CronSchedule(cronExpression))
.Build();
await Scheduler.ScheduleJob(job, trigger);
}
private static IJobDetail CreateJob<T>(Dictionary<string, object>? data, string group) where T : IJob
{
if (_jobDetails.ContainsKey(typeof(T).Name)) return _jobDetails[typeof(T).Name];
var job = JobBuilder.Create<T>()
.WithIdentity(typeof(T).Name, group)
.Build();
if (data != null && data.Count > 0)
foreach (var item in data)
job.JobDataMap.Add(item.Key, item.Value);
_jobDetails[typeof(T).Name] = job;
return job;
}
public static async Task PauseJob<T>(string group = "defaultGroup")
{
if (_jobDetails.ContainsKey(typeof(T).Name)) await Scheduler.PauseJob(JobKey.Create(typeof(T).Name, group));
}
public static async Task ResumeJob<T>(string group = "defaultGroup")
{
if (_jobDetails.ContainsKey(typeof(T).Name)) await Scheduler.ResumeJob(JobKey.Create(typeof(T).Name, group));
}
public static async Task Shutdown()
{
if (!Scheduler.IsShutdown) await Scheduler.Shutdown();
}
public static async Task TriggerOnceImmediately<T>(string group = "defaultGroup") where T : IJob
{
if (!_jobDetails.ContainsKey(typeof(T).Name)) return;
await Scheduler.TriggerJob(new JobKey(typeof(T).Name, group));
}
}