JXMovies/Core/JXCMS.Core/TimingTask/QuartzTask.cs

93 lines
2.9 KiB
C#
Raw Normal View History

2020-02-10 22:30:27 +08:00
using System;
2020-02-12 15:23:34 +08:00
using System.Collections.ObjectModel;
2020-02-10 22:30:27 +08:00
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
namespace JXCMS.Core.TimingTask
{
public class QuartzTask
{
private ISchedulerFactory _schedulerFactory;
private IScheduler _scheduler;
private QuartzTask()
{
_schedulerFactory = new StdSchedulerFactory();
_scheduler = _schedulerFactory.GetScheduler().Result;
_scheduler.Start();
}
private static QuartzTask _instance;
public static QuartzTask Instance()
{
if (_instance == null)
{
_instance = new QuartzTask();
}
return _instance;
}
2020-02-12 15:23:34 +08:00
public async Task<bool> AddTask(Type jobType, string cron, string jobName, string jobGroup = "default", params (string name, object value)[] param)
2020-02-10 22:30:27 +08:00
{
2020-02-12 15:23:34 +08:00
var time = DateTime.Now;
var job = JobBuilder.Create(jobType).WithIdentity(jobName, jobGroup).Build();
var trigger = TriggerBuilder.Create().WithIdentity(jobName + "trigger").StartNow().WithCronSchedule(cron).Build();
foreach (var par in param)
{
job.JobDataMap.Put(par.name, par.value);
}
var offset = await _scheduler.ScheduleJob(job, trigger);
2020-02-10 22:30:27 +08:00
return true;
}
2020-02-12 15:23:34 +08:00
public async Task<bool> DeleteTask(string jobName, string jobGroup = "default")
{
return await _scheduler.DeleteJob(new JobKey(jobName, jobGroup));
}
public async Task<bool> DeleteTasks(ReadOnlyCollection<JobKey> jobKeys)
{
return await _scheduler.DeleteJobs(jobKeys);
}
2020-02-16 22:11:24 +08:00
/// <summary>
/// Corn表达式的运行时间
/// </summary>
/// <param name="cron">表达式</param>
/// <param name="times">计算次数</param>
/// <param name="startTime">开始时间</param>
/// <returns></returns>
public static string GetCronSchedule(String cron, int times, DateTimeOffset startTime)
{
String timeSchedule = "";
if (!CronExpression.IsValidExpression(cron))
{
return "Cron表达式不合法!";
}
try
{
ITrigger trigger1 = TriggerBuilder.Create()
.WithCronSchedule(cron)
.StartNow()
.Build();
for (int i = 0; i < times; i++)
{
DateTimeOffset? s = trigger1.GetFireTimeAfter(startTime);
DateTime? time = s?.LocalDateTime;
timeSchedule = time?.ToString("F");
}
}
catch (System.Exception e)
{
timeSchedule = "未知时间";
}
return timeSchedule;
}
2020-02-10 22:30:27 +08:00
}
}