Quartz 定时任务 服务

1.服务初始化


using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using log4net;

namespace EohiQuartzService
{
    //窗体控制->委托
    public delegate void ServiceHeplerHandler(string[] args);           //开始
    public delegate void ServiceHeplerStopHandler();                            //停止
    public delegate void ServiceHeplerShowTaskHandler();                  //显示远程控制页面
    public partial class Service1 : ServiceBase
    {
         //日志
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


        public bool ServiceRunIsTrue { get; set; }    //服务运行状态
        public  ServiceHeplerHandler ServiceStratHandler;
        public  ServiceHeplerStopHandler ServiceStopHandler;
        public ServiceHeplerShowTaskHandler ServiceShowTaskHandler;
        public Service1()
        {
            QuarztHelper.Start();
            ServiceRunIsTrue = QuarztHelper.ServiceRunIsTrue;
            ServiceStratHandler += OnStart;
            ServiceStopHandler += OnStop;
            ServiceShowTaskHandler += ShowTaskManagers;
            InitializeComponent();
            string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "服务初始化;");
            log.Info(start);
        }

        protected override void OnStart(string[] args)
        {
            QuarztHelper.Start();
            ServiceRunIsTrue = QuarztHelper.ServiceRunIsTrue;
            string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "服务启动,ONSTART");
            log.Info(start);
        }

        protected override void OnStop()
        {
            QuarztHelper.Stop();
            ServiceRunIsTrue = QuarztHelper.ServiceRunIsTrue;
            string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "服务停止,ONSTOP");
            log.Info(start);
        }
        protected void ShowTaskManagers()
        {
            System.Diagnostics.Process.Start("http://localhost:39897/CrystalQuartzPanel.axd?menucode=008");
            string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "跳转远程管理页面,CrystalQuartzPanel.acd");
            log.Info(start);
        }
           
    }                            
}
 

 

2.Quartz初始化


using EohiQuartzService.Quarzt;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Quartz;
using log4net;


namespace EohiQuartzService
{
    public class QuarztHelper
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static Quartz.IScheduler scheduler = null;
        public static bool ServiceRunIsTrue { get; set; }
        public static void Stop()
        {
            try
            {
                if (scheduler != null)
                {
                    //if (scheduler.IsStarted)
                    //{
                    scheduler.Shutdown();
                    bool b = scheduler.IsStarted;
                    ServiceRunIsTrue = false;
                    //}
                }

                string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "停止Quartz服务成功!;");
                log.Info(start);


            }
            catch (Exception exp)
            {
                string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "停止Quartz服务失败!;"+exp.Message);
                log.Info(start);
                Console.WriteLine(exp.Message);
                //throw;
            }
        }
        public static void Start()
        {
            try
            {
                if (scheduler != null)
                {
                    if (!scheduler.IsStarted)
                    {
                        scheduler.Start();
                        ServiceRunIsTrue = true;
                    }
                }
                else
                {

                #region 测试.
                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"] = "555";
                properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
                properties["quartz.scheduler.exporter.channelType"] = "tcp";

                var schedulerFactory = new Quartz.Impl.StdSchedulerFactory(properties);
                 scheduler = schedulerFactory.GetScheduler();
              
                scheduler.Start();
                    string startm = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "初始化Quartz服务开始运行!;" );
                    log.Info(startm);
                }


                #endregion


                #region 原
                //var properties = new NameValueCollection();
                properties["quartz.scheduler.instanceName"] = "RemoteServerSchedulerClient";
                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"] = "555";
                //properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
                //properties["quartz.scheduler.exporter.channelType"] = "tcp";

                scheduler = StdSchedulerFactory.GetDefaultScheduler(properties);
                //var schedulerFactory = new StdSchedulerFactory(properties);
                //scheduler = schedulerFactory.GetScheduler();
                //scheduler.Start(); 
                #endregion
                //
                List<Model_QuartzNetItem> itemList = QuartzNetService.GetList();
                {
                    foreach (Model_QuartzNetItem itm in itemList)
                    {
                        if (itm.Quartzstatus != "启动")
                            continue;

                        if (itm.Jobtype.ToLower() == "http")
                        {
                            HttpJob_Create(itm);
                        }
                    }
                }

                ServiceRunIsTrue = true;

                string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "启动Quartz服务成功总有"+itemList.Count+"条任务");
                log.Info(start);

            }
            catch (Exception exp)
            {


                //初始化log4net
                string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "启动Quartz服务失败:" + exp.Message);
                log.Info(start);
                ServiceRunIsTrue = false;

                Console.WriteLine(exp.Message);
                //throw;
            }
        }


        private static void HttpJob_Create(Model_QuartzNetItem itm)
        {
            try
            {
                Quartz.IJobDetail job = Quartz.JobBuilder.Create<HttpRequestJob>()
               .WithIdentity("job-" + itm.Id.ToString() )
               .WithDescription(itm.Quartzname+"|"+itm.Quartznote)
               .UsingJobData("httpurl", itm.Jobpars)
               .Build();

                //ITrigger trigger = TriggerBuilder.Create()
                //  .WithIdentity("trigger" + itm.Id.ToString(), "triggergroup" + itm.Id.ToString())
                //  .WithSimpleSchedule(t =>
                //    t.WithIntervalInSeconds(5)
                //     .RepeatForever())
                //     .Build();

                Quartz.ITrigger trigger = Quartz.TriggerBuilder.Create()
                                   .WithIdentity("trigger-" + itm.Id.ToString())
                                   .StartNow()
                                   .WithCronSchedule(itm.Crontrigger)    //时间表达式,5秒一次     
                                   .Build();

                //
                scheduler.ScheduleJob(job, trigger);
            }
            catch (Exception exp)
            {
                string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "HttpJob_Create方法 Quartz请求任务失败:" + exp.Message);
                log.Info(start);
                //throw;
            }
        }
        private static void HttpJob_Remove(Model_QuartzNetItem itm)
        {
            try
            {
                string jobid = "job-" + itm.Id.ToString();
                string triggerid = "trigger-" + itm.Id.ToString();
                JobKey jobKey = new JobKey(jobid);
                TriggerKey triggerKey = new TriggerKey(triggerid);
                scheduler.PauseJob(jobKey);// 停止触发器  
                scheduler.UnscheduleJob(triggerKey);// 移除触发器  
                scheduler.DeleteJob(jobKey);// 删除任务  
            }
            catch (Exception exp)
            {

                string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "HttpJob_Remove方法 删除Quartz请求任务失败:" + exp.Message);
                log.Info(start);
                //throw;
            }
        }

        public static void JoinJob(int jobid)
        {
            try
            {
                Model_QuartzNetItem itm = QuartzNetService.GetById(jobid);
                if (itm == null)
                    return;
                if (itm.Jobtype.ToLower() == "http")
                {
                    if (itm.Quartzstatus == "停止")
                    {
                        //移除
                        HttpJob_Remove(itm);
                    }
                    else
                    {
                        HttpJob_Create(itm);
                    }
                }
               
            }
            catch (Exception exp)
            {
                string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "JoinJob方法 JoinJobQuartz请求任务失败:" + exp.Message);
                log.Info(start);
                //throw;
            }
        }
    }
}

2.1   [DisallowConcurrentExecution]     //禁止并发,一般当任务的执行时间大于定时时间时防止并发,

using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace EohiQuartzService
{
    [DisallowConcurrentExecution]     //禁止并发
    public class HttpRequestJob : IJob
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        //public string httpurl = "http://www.baidu.com";
        public void Execute(IJobExecutionContext context)
        {
            /*
            var reportDirectory = string.Format("~/reports/{0}/", DateTime.Now.ToString("yyyy-MM"));
            reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory);
            if (!Directory.Exists(reportDirectory))
            {
                Directory.CreateDirectory(reportDirectory);
            }
            var dailyReportFullPath = string.Format("{0}report_{1}.log", report

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值