using System.Reflection;
using MasstransferCommon.Annotation;
using MasstransferCommon.Utils;
using Quartz;
using Quartz.Impl;
namespace MasstransferCommon.Scheduler;
///
/// 定时任务器
///
public class QuartzScheduler
{
private readonly IScheduler _scheduler;
private QuartzScheduler()
{
var schedulerFactory = new StdSchedulerFactory();
_scheduler = schedulerFactory.GetScheduler().Result;
}
public static QuartzScheduler Instance { get; } = new();
///
/// 启动定时任务器
///
public async Task StartAsync()
{
await _scheduler.Start();
// 查找所有带有 ScheduledJobAttribute 的类
var jobs = AssemblyUtil.GetTypesByAttribute(typeof(ScheduledJobAttribute));
foreach (var job in jobs)
{
var attribute = job.GetCustomAttribute();
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);
}
}
///
/// 停止定时器
///
public async Task StopAsync()
{
await _scheduler.Shutdown();
}
}