Quartz.Net使用小列

前些时候我发过一篇文章,是讲在Webconfig中设定一线线程来做一件JOB的方式,TIMER会应为被垃圾回收机制回收掉而不执行JOB的问题,有朋友给我推荐了QUARTZ.NET这个插件,在百度上面百度了一番,发现使用起来还是比较复杂的,抱着试试看的心态写了几个列子,发现都离不开在Webconfig上面配置一番,对于这点觉得不爽,于是尝试把WEBCONFIG上面的配置项去掉,发现程序还是能够正常执行的,这样这样一个JOB就非常的简单了

首先在WEBCONFIG上面启动这样的一个JOB,这个是必不可少的

    void Application_Start(object sender, EventArgs e)
    {
        ServerHelper.DAL.WriteLogScheduler.Instance.Start();

    }

    void Application_End(object sender, EventArgs e)
    {
        ServerHelper.DAL.WriteLogScheduler.Instance.Stop();
    }

然后按照网上给出的列子实现了一个JOB,这个JOB分成两个类

public class WriteLogScheduler
    {
        static ISchedulerFactory _sf = new StdSchedulerFactory();
        static IScheduler _sched = _sf.GetScheduler();
        static WriteLogScheduler _instance = null;
        static object lockObj = new object();

        /// <summary>
        /// 线程安全的单例对象
        /// </summary>
        public static WriteLogScheduler Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObj)
                    {
                        if (_instance == null)
                        {
                            _instance = new WriteLogScheduler();
                        }
                    }
                }
                return _instance;
            }
        }

        public void Start()
        {
            Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(typeof(WriteLogScheduler));
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);
            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<WriteLogJob>().WithIdentity("job1", "group1").Build();

            // Trigger the job to run on the next round minute
            //   ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger1", "group1").StartAt(runTime).Build();
            Quartz.Impl.Triggers.CronTriggerImpl trigger = new Quartz.Impl.Triggers.CronTriggerImpl("trigger1", "group1", "0 * 0-23 * * ?");
            //这个地方与大多数给的列子不一样,直接定义了每天的每分钟来执行JOB
            _sched.ScheduleJob(job, trigger);

            _sched.Start();
        }
        public void Stop()
        {
            _sched.Shutdown(true);
        }
    }

然后是实现JOB

class WriteLogJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Common.Common.LogManager.GetInstance().Info("脚本运行");
            string hour = Common.Common.Base64.GetAppSettings("Hour");
            int ihour = 22;
            if (!string.IsNullOrEmpty(hour))
            {
                ihour = Convert.ToInt32(hour);
            }
            if (DateTime.Now.Hour == ihour && DateTime.Now.Minute == 0)
            {
                Common.Common.LogManager.GetInstance().Info("时间条件符合,进行邮件发送");
                new ServerHelper.DAL.Mail().SendMail();
            }
        }
    }

这样一个简单的JOB就完成了

你可能感兴趣的:(quartz)