使用FluentScheduler實現定時任務管理


之前定時任務一直用的Windows服務,前段時間發現FluentScheduler這個框架,他跟Quarz.Net,Hangfire一樣都是任務調度框架,但是相對使用而言我覺得FluentScheduler更加方便簡單一些.

1.新建一個mvc項目

2.nuget直接安裝FluentScheduler

3.新建一個類

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

namespace FluentSchedulerWeb
{
    using FluentScheduler;
    using System.Diagnostics;
    using System.IO;
    using System.Threading;
    public class MyJob : Registry
    {
        public MyJob()
        {
            // 每2秒一次循環
            Schedule<MyJob1>().ToRunNow().AndEvery(2).Seconds();

            // 5秒后,只一次
            Schedule<MyOtherJob>().ToRunOnceIn(5).Seconds();

            //每天晚上21:15分執行
            Schedule(() => Console.WriteLine("Timed Task - Will run every day at 9:15pm: " + DateTime.Now)).ToRunEvery(1).Days().At(21, 15);

            // 每個月的執行
            Schedule(() =>
            {
                Console.WriteLine("Complex Action Task Starts: " + DateTime.Now);
                Thread.Sleep(1000);
                Console.WriteLine("Complex Action Task Ends: " + DateTime.Now);
            }).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);

            //先執行第一個Job、再執行第二個Job;完成后等5秒繼續循環
            Schedule<MyFirstJob>().AndThen<MySecoundJob>().ToRunNow().AndEvery(5).Seconds();
        }
    }

    public class MyJob1 : IJob
    {

        void IJob.Execute()
        {
            Trace.WriteLine("循環每2秒執行一次;現在時間是:" + DateTime.Now);
            var str = "循環每2秒執行一次;現在時間是:" + DateTime.Now.ToString();
            System.IO.StreamWriter writer = null;
            try
            {


                //寫入日志 
                string path = string.Empty;
                path = @"F:\ErrorLogs\";
                //不存在則創建錯誤日志文件夾
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += string.Format(@"\{0}.txt", DateTime.Now.ToString("yyyy-MM-dd"));

                writer = !System.IO.File.Exists(path) ? System.IO.File.CreateText(path) : System.IO.File.AppendText(path); //判斷文件是否存在,如果不存在則創建,存在則添加
                writer.WriteLine(str);
                writer.WriteLine("********************************************************************************************");
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
    }

    public class MyOtherJob : IJob
    {

        void IJob.Execute()
        {
            Trace.WriteLine("5秒后只執行一次 ,現在時間是:" + DateTime.Now);
        }
    }

    public class MyFirstJob : IJob
    {

        void IJob.Execute()
        {
            Trace.WriteLine("執行第一個 Job ,現在時間是:" + DateTime.Now);
        }
    }
    public class MySecoundJob : IJob
    {

        void IJob.Execute()
        {
            Trace.WriteLine("執行第二個 Job ,現在時間是:" + DateTime.Now);
        }
    }

}

4.Global.asax中啟用FluentScheduler

 protected void Application_Start()
{
   AreaRegistration.RegisterAllAreas();
   RouteConfig.RegisterRoutes(RouteTable.Routes);
   //啟用
   JobManager.Initialize(new MyJob());
}

這樣FluentScheduler就可以使用了

 

當然在使用過程中發布到iis必然面臨着iis回收的問題

下面兩種方法親測可用

方法一.IIS預加載

(1)修改應用程序池啟動模式

 

 (2)開啟對應網站預加載(IIS7.5沒有這個)

 

(3).增加配置編輯器,編寫默認預加載的請求頁面

hostName是地址,initializationPage是要加載的頁面

這樣預加載就搞定了

方法二:通過代碼實現iis回收之后自動訪問頁面來喚醒服務

using FluentScheduler;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FluentSchedulerWeb2
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //啟用
            JobManager.Initialize(new MyJob());
        }

        protected void Application_End()
        {
            WriteLog("進程即將被IIS回收"+DateTime.Now);
            WriteLog("重新訪問一個頁面,以喚醒服務" + DateTime.Now);
            string strURL = System.Configuration.ConfigurationManager.AppSettings["homeURL"].ToString();
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.IO.Stream stream = wc.OpenRead(strURL);
                System.IO.StreamReader reader = new StreamReader(stream);
                string html = reader.ReadToEnd();
                if (!string.IsNullOrWhiteSpace(html))
                {
                    WriteLog("喚醒程序成功" + DateTime.Now);
                }
                reader.Close();
                reader.Dispose();
                stream.Close();
                stream.Dispose();
                wc.Dispose();
            }
            catch (Exception ex)
            {
                WriteLog("喚醒異常"+ex.Message+DateTime.Now);
            }
        }

        public void WriteLog(string str)
        {
            System.IO.StreamWriter writer = null;
            try
            {
                //寫入日志 
                string path = string.Empty;
                path = @"F:\ErrorLogs\";
                //不存在則創建錯誤日志文件夾
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += string.Format(@"\{0}.txt", DateTime.Now.ToString("yyyy-MM-dd"));

                writer = !System.IO.File.Exists(path) ? System.IO.File.CreateText(path) : System.IO.File.AppendText(path); //判斷文件是否存在,如果不存在則創建,存在則添加
                writer.WriteLine(str);
                writer.WriteLine("********************************************************************************************");
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
    }
}

這樣就搞定了 

 

那么,我們如何測試呢,可以更改IIS的回收時間

在應用程序池中右鍵當前應用程序池,正在回收

 

設置回收間隔  我設置1分鍾

 

這樣可以再去看日志  

 


免責聲明!

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



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