MasstransferExporter/MasstransferCommon/Scheduler/QuartzScheduler.cs

57 lines
1.4 KiB
C#
Raw Permalink Normal View History

using System.Reflection;
using MasstransferCommon.Annotation;
using MasstransferCommon.Utils;
using Quartz;
using Quartz.Impl;
namespace MasstransferCommon.Scheduler;
/// <summary>
/// 定时任务器
/// </summary>
public class QuartzScheduler
{
private readonly IScheduler _scheduler;
private QuartzScheduler()
{
var schedulerFactory = new StdSchedulerFactory();
_scheduler = schedulerFactory.GetScheduler().Result;
}
public static QuartzScheduler Instance { get; } = new();
/// <summary>
/// 启动定时任务器
/// </summary>
public async Task StartAsync()
{
await _scheduler.Start();
// 查找所有带有 ScheduledJobAttribute 的类
var jobs = AssemblyUtil.GetTypesByAttribute(typeof(ScheduledJobAttribute));
foreach (var job in jobs)
{
var attribute = job.GetCustomAttribute<ScheduledJobAttribute>();
var jobDetail = JobBuilder.Create(job)
.WithIdentity(job.Name)
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity($"{job.Name}.trigger")
.WithCronSchedule(attribute!.Cron)
.Build();
await _scheduler.ScheduleJob(jobDetail, trigger);
}
}
/// <summary>
/// 停止定时器
/// </summary>
public async Task StopAsync()
{
await _scheduler.Shutdown();
}
}