namespace IStation.DataDockingSocket
|
{
|
/// <summary>
|
/// Modbus辅助类
|
/// </summary>
|
public class SendInstructionJobHelper
|
{
|
private static IScheduler _sched;//调度器
|
|
/// <summary>
|
/// 开始任务
|
/// </summary>
|
public static async void StartJob(Yw.Model.IMonitorDataDockingSession session, InstructionItem item)
|
{
|
if (session == null)
|
return;
|
if (!session.IsConnected)
|
return;
|
if (item == null)
|
return;
|
if (string.IsNullOrEmpty(item.Instruction))
|
return;
|
if (item.RuleItems == null || item.RuleItems.Count < 1)
|
return;
|
|
LogHelper.Info($"{session.SessionName} 开始处理发送指令任务,指令:{item.Instruction} !");
|
|
var jobName = SendInstructionJobNameHelper.GetJobName(session, item.Instruction);
|
var jobGroupName = SendInstructionJobNameHelper.GetJobGroupName(session, item.Instruction);
|
var triggerName = SendInstructionJobNameHelper.GetTriggerName(session, item.Instruction);
|
|
//判断是否存在
|
if (_sched != null)
|
{
|
var triggerKey = new TriggerKey(triggerName, jobGroupName);
|
if (await _sched.CheckExists(triggerKey))
|
{
|
LogHelper.Info($"{session.SessionName} 中,指令:{item.Instruction} 的主动请求数据任务已经开启,无需重复开启!");
|
return;
|
}
|
}
|
|
//判断是否开启调取器
|
if (_sched == null)
|
{
|
// 1.创建scheduler的引用
|
var fac = new Quartz.Impl.StdSchedulerFactory();
|
_sched = await fac.GetScheduler();
|
|
//2.启动 scheduler
|
await _sched.Start();
|
}
|
|
//3.创建任务
|
var job = JobBuilder.Create<SendInstructionJob>()
|
.WithIdentity(jobName, jobGroupName)
|
.Build();
|
job.JobDataMap.Put(SendInstructionJob.Session, session);
|
job.JobDataMap.Put(SendInstructionJob.Instruction, BitTransfer.FromString(item.Instruction));
|
|
//4.创建Trigger
|
var trigger = TriggerBuilder.Create()
|
.WithIdentity(triggerName, jobGroupName)
|
.WithSimpleSchedule(x => x.WithIntervalInSeconds(item.Frequency).RepeatForever()
|
.WithMisfireHandlingInstructionNextWithRemainingCount())
|
.Build();
|
|
//5.加入调度管理器
|
await _sched.ScheduleJob(job, trigger);
|
session.SessionClosedEvent += () => CancelJob(session, item.Instruction);
|
LogHelper.Info($"{session.SessionName} 中,指令:{item.Instruction} 的主动请求数据线程开启成功!");
|
}
|
|
/// <summary>
|
/// 取消任务
|
/// </summary>
|
private static async void CancelJob(Yw.Model.IMonitorDataDockingSession session, string instruction)
|
{
|
if (_sched == null)
|
return;
|
LogHelper.Info($"{session.SessionName} 正打算终止主动请求数据任务");
|
var triggerName = SendInstructionJobNameHelper.GetTriggerName(session, instruction);
|
var jobGroupName = SendInstructionJobNameHelper.GetJobGroupName(session, instruction);
|
var triggerKey = new TriggerKey(triggerName, jobGroupName);
|
if (await _sched.CheckExists(triggerKey))
|
{
|
await _sched.UnscheduleJob(triggerKey);
|
LogHelper.Info($"{session.SessionName},指令:{instruction} 主动请求数据任务终止成功");
|
}
|
else
|
{
|
LogHelper.Info($"{session.SessionName},指令:{instruction} 主动请求数据任务不存在");
|
}
|
}
|
|
|
|
|
}
|
}
|