Quartz.Net與MVC結合定時任務

來源:互聯網
上載者:User

標籤:sharp   部分   img   text   epo   tin   通過   direct   最簡   

1.首先,我們開啟Visual Studio 2015,建立一個ASP.NET MVC的Web應用程式項目。

2.然後通過封裝管理員控制台來安裝Quartz.Net組件。

Quartz.Net一個最簡單任務至少包括三部分實現:job(作業),trigger(觸發器)以及scheduler(調度器)。

其中job 是你需要在一個定時任務中具體執行的商務邏輯,trigger則規定job何時並按照何種規則執行,最終job和trigger會被註冊到 scheduler(調度器)中,scheduler負責協調job和trigger的運行。

3.建立Job類

 public class ReportJob : IJob  {    public void Execute(IJobExecutionContext context)//必須實現IJob介面下的Execute方法    {      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", reportDirectory, DateTime.Now.Day);      var logContent = string.Format("{0}==>>{1}{2}", DateTime.Now, "create new log.", Environment.NewLine);      File.AppendAllText(dailyReportFullPath, logContent);    }  }

4.建立觸發器trigge

 public class ReportJobScheduler    {        public static void Start()        {            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); //從工廠中擷取一個調度器執行個體化            scheduler.Start();   //開始調度器            IJobDetail job = JobBuilder.Create<ReportJob>().Build();//建立一個作業            ITrigger trigger = TriggerBuilder.Create()                .WithSimpleSchedule(t =>                t.WithIntervalInSeconds(5) //觸發執行,5s一次                .RepeatForever())          //重複執行                .Build();            scheduler.ScheduleJob(job,trigger);       //把作業,觸發器加入調度器。         }    }

5.把這個任務放到項目程式的全域cs檔案(Global.asax)的Application_Start方法中來執行.

 protected void Application_Start()        {            AreaRegistration.RegisterAllAreas();            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);            BundleConfig.RegisterBundles(BundleTable.Bundles);            //在這裡調用            ReportJobScheduler.Start();        }

6.之後啟動網站,便會發現網站的根目錄下有定時任務產生的檔案和檔案夾

7.這隻是個簡單的例子,參照http://www.cnblogs.com/bobositlife/p/aspnet-mvc-csharp-quartz-net-timer-task-scheduler.html,這篇部落格做的實驗。

本實驗原始碼:https://git.oschina.net/sdadx/Quartz.Net/tree/master/

 

Quartz.Net與MVC結合定時任務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.