定时任务管理类
实现了如下功能:
1、对定时任务进行管理 2、创建定时任务,需要给定时任务一个job的名称 3、判断给定的job的任务是否已存在 4、停止定时任务的功能
namespace MyUKD.Quartz
{
public class QuartzSchedulerMgr
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private static ISchedulerFactory schedulerFactory;
private static IScheduler scheduler;
/// <summary>
/// 初始化处理
/// </summary>
public static async void Initialize()
{
NameValueCollection props = new NameValueCollection
{
{"quartz.serializer.type","binary" }
};
LogProvider.IsDisabled = true;
schedulerFactory = new StdSchedulerFactory(props);
scheduler = await schedulerFactory.GetScheduler();
await scheduler.Start();
}
public static async void UnInitialize()
{
await scheduler.PauseAll();
//var groups = await scheduler.GetJobGroupNames();
foreach (string g in await scheduler.GetJobGroupNames())
{
await scheduler.DeleteJobs(await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(g)));
await scheduler.UnscheduleJobs(await scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(g)));
}
}
public static IScheduler GetScheduler()
{
return scheduler;
}
/// <summary>
///
/// </summary>
/// <param name="jobName"></param>
/// <returns></returns>
public static async Task<bool> UnScheduleJob(string jobName)
{
try
{
bool exist = await ExistJob(jobName);
if (exist)
{
JobKey key = JobKey.Create(jobName, $"{jobName}-JobGroup");
TriggerKey triggerKey = new TriggerKey(jobName, $"{jobName}-TriggerGroup");
await scheduler.PauseJob(key);
bool unScheduleJob = await scheduler.UnscheduleJob(triggerKey);
bool delete = await scheduler.DeleteJob(key);
System.Diagnostics.Debug.WriteLine($"UnScheduleJob:JobKey:{key.Group}-{key.Name},TriggerKey:{triggerKey.Group}-{triggerKey.Name}");
return unScheduleJob && delete;
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e);
Logger.Error(e);
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="jobName"></param>
/// <returns></returns>
public static async Task<bool> ExistJob(string jobName)
{
JobKey key = JobKey.Create(jobName, $"{jobName}-JobGroup");
return await scheduler.CheckExists(key);
}
/// <summary>
/// 创建定时任务:确定执行间隔,确定执行次数的任务
/// </summary>
/// <typeparam name="T">继承IJob的类</typeparam>
/// <param name="jobName">任务的名称</param>
/// <param name="intervalInSeconds">多长时间执行一次</param>
/// <param name="repeatCount">重复执行次数</param>
/// <returns></returns>
public static async Task<DateTimeOffset> CreateJob<T>(string jobName, int intervalInSeconds, int repeatCount) where T : IJob
{
IJobDetail job = JobBuilder.Create<T>().WithIdentity(jobName, $"{jobName}-JobGroup").Build();
ITrigger trigger = TriggerBuilder.Create().WithIdentity(jobName, $"{jobName}-TriggerGroup")
.WithSimpleSchedule(x => x.WithIntervalInSeconds(intervalInSeconds).WithRepeatCount(repeatCount))
.Build();
return await scheduler.ScheduleJob(job, trigger);
}
/// <summary>
/// 创建定时任务:确定执行间隔,确定执行次数的任务
/// </summary>
/// <typeparam name="T">继承IJob的类</typeparam>
/// <param name="jobName">任务的名称</param>
/// <param name="intervalInSeconds">多长时间执行一次</param>
/// <param name="repeatCount">重复执行次数</param>
/// <param name="dataMap">向任务传递的参数</param>
/// <returns></returns>
public static async Task<DateTimeOffset> CreateJob<T>(string jobName, int intervalInSeconds, int repeatCount, JobDataMap dataMap)
where T : IJob
{
IJobDetail job = JobBuilder.Create<T>().WithIdentity(jobName, $"{jobName}-JobGroup").UsingJobData(dataMap).Build();
ITrigger trigger = TriggerBuilder.Create().WithIdentity(jobName, $"{jobName}-TriggerGroup").StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(intervalInSeconds).WithRepeatCount(repeatCount))
.Build();
return await scheduler.ScheduleJob(job, trigger);
}
/// <summary>
/// 创建定时任务:确定执行间隔,一直执行
/// </summary>
/// <typeparam name="T">继承IJob的类</typeparam>
/// <param name="jobName">任务的名称</param>
/// <param name="intervalInSeconds">多长时间执行一次</param>
/// <returns></returns>
public static async Task<DateTimeOffset> CreateJob<T>(string jobName, int intervalInSeconds) where T : IJob
{
IJobDetail job = JobBuilder.Create<T>().WithIdentity(jobName, $"{jobName}-JobGroup").Build();
ITrigger trigger = TriggerBuilder.Create().WithIdentity(jobName, $"{jobName}-TriggerGroup").StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(intervalInSeconds).RepeatForever())
.Build();
System.Diagnostics.Debug.WriteLine($"CreateJob:{job.Description}-{trigger.Description}");
//Console.WriteLine($"CreateJob:{job.Description}-{trigger.Description}");
return await scheduler.ScheduleJob(job, trigger);
}
/// <summary>
/// 创建定时任务:确定执行间隔,一直执行
/// </summary>
/// <typeparam name="T">继承IJob的类</typeparam>
/// <param name="jobName">任务的名称</param>
/// <param name="intervalInSeconds">多长时间执行一次</param>
/// <param name="dataMap">向任务传递的参数</param>
/// <returns></returns>
public static async Task<DateTimeOffset> CreateJob<T>(string jobName, int intervalInSeconds, JobDataMap dataMap)
where T : IJob
{
IJobDetail job = JobBuilder.Create<T>().WithIdentity(jobName, $"{jobName}-JobGroup").UsingJobData(dataMap).Build();
ITrigger trigger = TriggerBuilder.Create().WithIdentity(jobName, $"{jobName}-TriggerGroup").StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(intervalInSeconds).RepeatForever())
.Build();
return await scheduler.ScheduleJob(job, trigger);
}
/// <summary>
/// 创建任务,根据cron表达式确定任务执行的工作
/// </summary>
/// <typeparam name="T">继承IJob的类</typeparam>
/// <param name="jobName">任务的名称</param>
/// <param name="cronTime">cron表达式</param>
/// <returns></returns>
public static async Task<DateTimeOffset> CreateJob<T>(string jobName, string cronTime) where T : IJob
{
IJobDetail job = JobBuilder.Create<T>().WithIdentity(jobName, $"{jobName}-JobGroup").Build();
ICronTrigger trigger = new CronTriggerImpl(jobName, $"{jobName}-TriggerGroup", cronTime);
return await scheduler.ScheduleJob(job, trigger);
}
/// <summary>
/// 创建任务,根据cron表达式确定任务执行的工作
/// </summary>
/// <typeparam name="T">继承IJob的类</typeparam>
/// <param name="jobName">任务的名称</param>
/// <param name="cronTime">cron表达式</param>
/// <param name="dataMap">向任务传递的参数</param>
/// <returns></returns>
public static async Task<DateTimeOffset> CreateJob<T>(string jobName, string cronTime, JobDataMap dataMap) where T : IJob
{
IJobDetail job = JobBuilder.Create<T>().WithIdentity(jobName, $"{jobName}-JobGroup").UsingJobData(dataMap).Build();
ICronTrigger trigger = new CronTriggerImpl(jobName, $"{jobName}-TriggerGroup", cronTime);
return await scheduler.ScheduleJob(job, trigger);
}
}
}
定时任务获取正在执行的JOB
1、首先获取Scheduler
var scheduler = QuartzSchedulerMgr.GetScheduler()
2、获取Scheduler中的JobGroupNames
var groups = scheduler.GetJobGroupNames();
3、for循环逐个对每个group进行处理,可以获取到job的名称信息,以及触发器trigger的下次执行时间等内容
foreach (var groupName in groups)
{
foreach (var jobKey in QuartzSchedulerMgr.GetScheduler().GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName)))
{
string jobName = jobKey.Name;
string jobGroup = jobKey.Group;
var triggers = QuartzSchedulerMgr.GetScheduler().GetTriggersOfJob(jobKey);
foreach (ITrigger trigger in triggers)
{
trigger.GetNextFireTimeUtc();
}
}
}
注:下次触发时间为UTC时间,我们这边是北京时间,需要进行转换
TimeZone.CurrentTimeZone.ToLocalTime(Convert.ToDateTime(triggers.ToList()[0].GetNextFireTimeUtc().ToString()))
·END·
DotNetCore学习站
超乎想象的.NET Core学习资源
微信号:DotNetCore学习站