1. 程式人生 > WINDOWS開發 >WebAPI中的定時任務詳解-使用Quartz.Net

WebAPI中的定時任務詳解-使用Quartz.Net

  最近做WebAPI定時任務,網上搜了好多,發現對於小白來說並不太友好,Quartz.Net 2.X和3.X變化太大

整理一下自己做的一些體驗 基於Quartz.Net 2.X

1.定時指令碼

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace WF.BPM.WebAPI.Job
{
    
/// <summary> /// 定時任務 /// </summary> public class JobScheduler { /// <summary> /// 分鐘 /// </summary> public static int Minute = Convert.ToInt32(ConfigurationManager.AppSettings["Minute"]); /// <summary> /// 開始任務 /// </summary>
/// <returns></returns> public static void Start() { // 建立作業排程器 ISchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = factory.GetScheduler(); // 建立作業 IJobDetail job = JobBuilder.Create<SendSMSJob>() .WithIdentity(
"SendSMSJob","SendSMSJobGroup") .Build(); // 建立觸發器,每3min執行一次 ITrigger trigger = TriggerBuilder.Create() .WithIdentity("SendSMSTrigger","SendSMSGroup") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInMinutes(Minute) .RepeatForever()) .Build(); // 加入到作業排程器中 scheduler.ScheduleJob(job,trigger); scheduler.Start(); } } }

2.傳送程式碼

    /// <summary>
    /// 傳送簡訊
    /// </summary>
    public class SendSMSJob : IJob
    {


        /// <summary>
        /// 失敗次數
        /// </summary>
        public static int ErrorCount = Convert.ToInt32(ConfigurationManager.AppSettings["ErrorCount"]);
        public static int IsExecute = Convert.ToInt32(ConfigurationManager.AppSettings["IsExecute"]);
        string ConnectionString = ConfigurationManager.ConnectionStrings["K2SlnConnectionString"].ConnectionString;

        /// <summary>
        /// 執行方法
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            if (IsExecute == 1)
            {
               SendSMSBLL.MainSend();
            }
        }
    }

3.加入到Global.asax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WF.BPM.WebAPI.Job;

namespace WF.BPM.WebAPI
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //註冊定時任務
            JobScheduler.Start();
        }
    }
}