asp.net mvc 如何定時執行任務(包含打開網站和關閉網站繼續執行)


第一步:下載Quartz.NET類庫源碼

下載地址:http://www.quartz-scheduler.net/

 

第二步:程序集成:

1.修改網站根目錄下的web.config文件,在configuration節增加:

  <configSections>
    <!--定時任務調度配置-->
    <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
    <!--/End 定時任務調度配置-->
  </configSections>
  <!--定時任務調度配置-->
  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging">
        <arg key="showLogName" value="true" />
        <arg key="showDataTime" value="true" />
        <arg key="level" value="DEBUG" />
        <arg key="dateTimeFormat" value="HH:mm:ss:fff" />
      </factoryAdapter>
    </logging>
  </common>
  <quartz>
    <add key="quartz.scheduler.instanceName" value="ExampleDefaultQuartzScheduler" />
    <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
    <add key="quartz.threadPool.threadCount" value="10" />
    <add key="quartz.threadPool.threadPriority" value="2" />
    <add key="quartz.jobStore.misfireThreshold" value="60000" />
    <add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz" />
  </quartz>
  <!--/End 定時任務調度配置-->

   注意:如果web.config已存在configSections節,請將configSections節內的配置復制到web.config的configSections節下。

 

2.編寫代碼:

   2.1 取得作業調度單一實例

 public class Scheduler
    {
        private static IScheduler _instance;
        private Scheduler()
        {
        }
        /// <summary>
        /// 獲得本類實例的唯一全局訪問點。
        /// </summary>
        /// <returns></returns>
        [CLSCompliant(false)]
        public static IScheduler GetIntance()
        {
            if (_instance == null)
            {
                ISchedulerFactory schedFact = new StdSchedulerFactory();
                _instance = schedFact.GetScheduler();
            }
            return _instance;
        }
    }

 

   2.2 定時作業調度器輔助類

public class JobHelper
    {
        #region 命名前綴(可以自行設置)

        /// <summary>
        ///     作業前綴
        /// </summary>
        public static string JobPerfix = "Job_";

        /// <summary>
        ///     作業分組前綴
        /// </summary>
        public static string GroupPerfix = "Group_";

        /// <summary>
        ///     作業觸發器前綴
        /// </summary>
        public static string TriggerPerfix = "Trigger_";

        #endregion

        #region 初始化作業實體

        /// <summary>
        ///     根據傳入類型初始化作業實體
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static JobKey GetJobKey<T>()
        {
            string name = typeof(T).FullName;
            return new JobKey(JobPerfix+name, GroupPerfix+name);
        }

        #endregion

        #region 開啟作業

        /// <summary>
        ///     開啟作業
        /// </summary>
        /// <param name="expression">表達式
        /// <returns></returns>
        public static bool StartJob<T>(string expression) where T : IJob
        {
            string name = typeof (T).FullName;
            IJobDetail job = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>());
            if (job != null &&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name))
            {
                return true;
            }
            if (!Scheduler.GetIntance().IsStarted)
            {
                Scheduler.GetIntance().Start();
            }
            if (job != null)
            {
                Scheduler.GetIntance().ResumeJob(GetJobKey<T>());
            }
            else
            {
                IJobDetail detail = JobBuilder.Create<T>().WithIdentity(JobPerfix+name, GroupPerfix+name).Build();
                ITrigger trigger = TriggerBuilder.Create()
                                                 .WithIdentity(TriggerPerfix+name)
                                                 .StartNow()
                                                 .WithCronSchedule(expression).ForJob(detail)
                                                 .Build();
                Scheduler.GetIntance().ScheduleJob(detail, trigger);
                return true;
            }

            return false;
        }

        #endregion

        #region 停止作業

        /// <summary>
        ///     停止作業
        /// </summary>
        /// <returns></returns>
        public static bool StopJob<T>()
        {
            string name = typeof (T).FullName;
            IJobDetail detail = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>());
            if (detail != null &&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name))
            {
                Scheduler.GetIntance().PauseJob(GetJobKey<T>());
                return true;
            }
            return false;
        }

        #endregion

        #region 刪除作業

        /// <summary>
        ///     刪除作業
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static bool DelJob<T>()
        {
            string name = typeof (T).FullName;
            IJobDetail detail = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>());
            if (detail != null&&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name))
            {
                Scheduler.GetIntance().PauseJob(GetJobKey<T>());
                Scheduler.GetIntance().DeleteJob(GetJobKey<T>());
                return true;
            }
            return false;
        }

        #endregion

        #region 取得作業運行狀態

        /// <summary>
        ///     取得作業運行狀態 true 正在運行,false 未在運行
        /// </summary>
        /// <returns></returns>
        public static bool GetJobStatus<T>()
        {
            string name = typeof(T).FullName;
            IJobDetail detail = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>());
            if (detail != null && !Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name))
            {
                return true;
            }
            return false;
        }

        public static bool GetJobStatus(string jobName)
        {
            string className = jobName.Substring(JobPerfix.Length);
            IJobDetail detail = Scheduler.GetIntance().GetJobDetail(new JobKey(jobName, GroupPerfix+className));
            if (detail != null &&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+className))
            {
                return true;
            }
            return false;
        }

        #endregion
    }

 

   2.3 一個示例的定時任務

 

 public class MyJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            ClsLogs log = new ClsLogs();
            log._logEvent("Hello at " + DateTime.Now.ToString(),"E:\\svn項目源碼\\平行世界svn\\trunk\\ParalWorld\\ParalWorld.Wenxin\\Log");
        }
    }

 

3.在網站Global.asax文件的Application_Start事件里開啟定時任務:

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //開啟定時任務調度
            JobHelper.StartJob<MyJob>("0 0/1 * * * ?");//每隔一分鍾執行一次任務
        }

至此程序集成完畢,可以根據自己設定的表達式觸發器來檢驗定時任務是否正常工作。

 

參考文檔:

1.Quartz.NET 官網:http://www.quartz-scheduler.net/documentation/index.html

2.簡單觸發器:http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html

3.表達式觸發器:http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html

 

 

Global.asax 可以是asp.net中應用程序或會話事件處理程序,我們用到了Application_Start(應用程序開始事件)和Application_End(應用程序結束事件)。當應用程序開始時,啟動一個定時器,用來定時執行任務YourTask()方法,這個方法里面可以寫上需要調用的邏輯代碼,可以是單線程和多線程。當應用程序結束時,如IIS的應用程序池回收,讓asp.net去訪問當前的這個web地址。這里需要訪問一個aspx頁面,這樣就可以重新激活應用程序。

protected void Application_End(object sender, EventArgs e) 

      
     { 
      
      
      //下面的代碼是關鍵,可解決IIS應用程序池自動回收的問題 
      
     Thread.Sleep(1000); 
      
      //這里設置你的web地址,可以隨便指向你的任意一個aspx頁面甚至不存在的頁面,目的是要激發Application_Start 
      
      string  url = "http://www.baidu.com"
      
     HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
      
     HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
      
     Stream receiveStream = myHttpWebResponse.GetResponseStream(); //得到回寫的字節流 
      
     } 
 
      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM