using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RMYY_CallCenter_Api.QuartzWorker
{
    public class QuartzWorker
    {
        readonly IScheduler _scheduler;
        public QuartzWorker()
        {
            var properties = new NameValueCollection();
            //properties["quartz.scheduler.instanceName"] = "RemoteServerSchedulerClient";
            // 设置线程池
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";

            // 远程输出配置
            properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
            properties["quartz.scheduler.exporter.port"] = "899";
            properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
            properties["quartz.scheduler.exporter.channelType"] = "tcp";

            var schedulerFactory = new StdSchedulerFactory(properties);
            _scheduler = schedulerFactory.GetScheduler();
        }

        /// <summary>
        /// 添加一个任务
        /// </summary>
        /// <param name="job"></param>
        public void AddWork(QuartzJob job)
        {
            var type = job.GetType();
            // 创建一个工作
            var jobName = "JobName_" + type;
            var jobGroup = "JobGroup_" + type;
            var jobDetail = new JobDetailImpl(jobName, jobGroup, type, true, true);
            // 创建一个触发器
            var trigger = new CronTriggerImpl("trigger" + jobName, "triggergroup" + jobName, jobName, jobGroup, job.CronExpression);
            _scheduler.AddJob(jobDetail, true);
            _scheduler.ScheduleJob(trigger);
        }

        /// <summary>
        /// 开始运行
        /// </summary>
        public void Start()
        {
            _scheduler.Start();
        }

        /// <summary>
        /// 停止运行
        /// </summary>
        public void Stop()
        {
            _scheduler.Shutdown(true);

        }
    }
}
