[C#][Quartz]帮助类
标签:dexp ide orm value std 等于 判断 server 远程管理
本文来自:http://www.cnblogs.com/pengze0902/p/6128558.html
///
/// 任务处理帮助类
///
public class QuartzHelper
{
public QuartzHelper() { }
public QuartzHelper(string quartzServer, string quartzPort)
{
Server = quartzServer;
Port = quartzPort;
}
///
/// 锁对象
///
private static readonly object Obj = new object();
///
/// 方案
///
private const string Scheme = "tcp";
///
/// 服务器的地址
///
public static string Server { get; set; }
///
/// 服务器的端口
///
public static string Port { get; set; }
///
/// 缓存任务所在程序集信息
///
private static readonly Dictionarystring, Assembly> AssemblyDict = new Dictionarystring, Assembly>();
///
/// 程序调度
///
private static IScheduler _scheduler;
///
/// 初始化任务调度对象
///
public static void InitScheduler()
{
try
{
lock (Obj)
{
if (_scheduler != null) return;
//配置文件的方式,配置quartz实例
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
_scheduler = schedulerFactory.GetScheduler();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 启用任务调度
/// 启动调度时会把任务表中状态为“执行中”的任务加入到任务调度队列中
///
public static void StartScheduler()
{
try
{
if (_scheduler.IsStarted) return;
//添加全局监听
_scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener(), GroupMatcher.AnyGroup());
_scheduler.Start();
//获取所有执行中的任务
List listTask = TaskHelper.GetAllTaskList().ToList();
if (listTask.Count > 0)
{
foreach (TaskModel taskUtil in listTask)
{
try
{
ScheduleJob(taskUtil);
}
catch (Exception e)
{
throw new Exception(taskUtil.TaskName,e);
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 启用任务
/// 任务信息
/// 是否删除原有任务
/// 返回任务trigger
///
public static void ScheduleJob(TaskModel task, bool isDeleteOldTask = false)
{
if (isDeleteOldTask)
{
//先删除现有已存在任务
DeleteJob(task.TaskID.ToString());
}
//验证是否正确的Cron表达式
if (ValidExpression(task.CronExpressionString))
{
IJobDetail job = new JobDetailImpl(task.TaskID.ToString(), GetClassInfo(task.AssemblyName, task.ClassName));
//添加任务执行参数
job.JobDataMap.Add("TaskParam", task.TaskParam);
CronTriggerImpl trigger = new CronTriggerImpl
{
CronExpressionString = task.CronExpressionString,
Name = task.TaskID.ToString(),
Description = task.TaskName
};
_scheduler.ScheduleJob(job, trigger);
if (task.Status == TaskStatus.STOP)
{
JobKey jk = new JobKey(task.TaskID.ToString());
_scheduler.PauseJob(jk);
}
else
{
List list = GetNextFireTime(task.CronExpressionString, 5);
foreach (var time in list)
{
LogHelper.WriteLog(time.ToString(CultureInfo.InvariantCulture));
}
}
}
else
{
throw new Exception(task.CronExpressionString + "不是正确的Cron表达式,无法启动该任务!");
}
}
///
/// 初始化 远程Quartz服务器中的,各个Scheduler实例。
/// 提供给远程管理端的后台,用户获取Scheduler实例的信息。
///
public static void InitRemoteScheduler()
{
try
{
NameValueCollection properties = new NameValueCollection
{
["quartz.scheduler.instanceName"] = "ExampleQuartzScheduler",
["quartz.scheduler.proxy"] = "true",
["quartz.scheduler.proxy.address"] =string.Format("{0}://{1}:{2}/QuartzScheduler", Scheme, Server, Port)
};
ISchedulerFactory sf = new StdSchedulerFactory(properties);
_scheduler = sf.GetScheduler();
}
catch (Exception ex)
{
throw new Exception(ex.StackTrace);
}
}
///
/// 删除现有任务
///
///
public static void DeleteJob(string jobKey)
{
try
{
JobKey jk = new JobKey(jobKey);
if (_scheduler.CheckExists(jk))
{
//任务已经存在则删除
_scheduler.DeleteJob(jk);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 暂停任务
///
///
public static void PauseJob(string jobKey)
{
try
{
JobKey jk = new JobKey(jobKey);
if (_scheduler.CheckExists(jk))
{
//任务已经存在则暂停任务
_scheduler.PauseJob(jk);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 恢复运行暂停的任务
///
/// 任务key
public static void ResumeJob(string jobKey)
{
try
{
JobKey jk = new JobKey(jobKey);
if (_scheduler.CheckExists(jk))
{
//任务已经存在则暂停任务
_scheduler.ResumeJob(jk);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 获取类的属性、方法
///
/// 程序集
/// 类名
private static Type GetClassInfo(string assemblyName, string className)
{
try
{
assemblyName = FileHelper.GetAbsolutePath(assemblyName + ".dll");
Assembly assembly = null;
if (!AssemblyDict.TryGetValue(assemblyName, out assembly))
{
assembly = Assembly.LoadFrom(assemblyName);
AssemblyDict[assemblyName] = assembly;
}
Type type = assembly.GetType(className, true, true);
return type;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 停止任务调度
///
public static void StopSchedule()
{
try
{
//判断调度是否已经关闭
if (!_scheduler.IsShutdown)
{
//等待任务运行完成
_scheduler.Shutdown(true);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 校验字符串是否为正确的Cron表达式
///
/// 带校验表达式
///
public static bool ValidExpression(string cronExpression)
{
return CronExpression.IsValidExpression(cronExpression);
}
///
/// 获取任务在未来周期内哪些时间会运行
///
/// Cron表达式
/// 运行次数
/// 运行时间段
public static List GetNextFireTime(string CronExpressionString, int numTimes)
{
if (numTimes 0)
{
throw new Exception("参数numTimes值大于等于0");
}
//时间表达式
ITrigger trigger = TriggerBuilder.Create().WithCronSchedule(CronExpressionString).Build();
IList dates = TriggerUtils.ComputeFireTimes(trigger as IOperableTrigger, null, numTimes);
List list = new List();
foreach (DateTimeOffset dtf in dates)
{
list.Add(TimeZoneInfo.ConvertTimeFromUtc(dtf.DateTime, TimeZoneInfo.Local));
}
return list;
}
public static object CurrentTaskList()
{
throw new NotImplementedException();
}
///
/// 获取当前执行的Task 对象
///
///
///
public static TaskModel GetTaskDetail(IJobExecutionContext context)
{
TaskModel task = new TaskModel();
if (context != null)
{
task.TaskID = Guid.Parse(context.Trigger.Key.Name);
task.TaskName = context.Trigger.Description;
task.RecentRunTime = DateTime.Now;
task.TaskParam = context.JobDetail.JobDataMap.Get("TaskParam") != null ? context.JobDetail.JobDataMap.Get("TaskParam").ToString() : "";
}
return task;
}
}
[C#][Quartz]帮助类
标签:dexp ide orm value std 等于 判断 server 远程管理
原文地址:https://www.cnblogs.com/z5337/p/9078839.html
评论