本文主要是介绍ASP.NET MVC中使用FluentScheduler任務定時器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
github作者示例地址 https://github.com/fluentscheduler/FluentScheduler
發佈web程序在IIS中,最好推薦將IIS改下配置,設置如下:
应用程序池-高级设置-启动模式:AlwaysRunning
应用程序-高级设置-常规-预加载已启用:True
//示例代碼:
using FluentScheduler;
namespace WebAppTimer.Models
{public class MyRegistry : Registry{public MyRegistry(){ //測試任務一,int jiange = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["jiange_seconds"]);Schedule<MyJob>().ToRunEvery(jiange).Seconds();//測試任務二,分鐘任務int coinMinutes = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["coinMinutes"]);Schedule<CoinValueJob>().ToRunEvery(coinMinutes).Minutes();}}
}public class MyJob : IJob{private readonly object _lockMin = new object();public void Execute(){//加鎖是為了保證在多線程環境下的準確lock (_lockMin){LogHelpter.AddLog("任務執行" + DateTime.Now.Ticks);} }}public class CoinValueJob : IJob{private readonly object _lock = new object();public void Execute(){//加鎖是為了保證在多線程環境下的準確lock (_lock){ LogHelpter.AddLog("幣價值平衡,任務執行");}}} public class MvcApplication : System.Web.HttpApplication{protected void Application_Start(){AreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);//初始化定時器任務FluentScheduler.JobManager.Initialize(new MyRegistry());}protected void Application_End(){LogHelpter.AddLog("进程即将被IIS回收");LogHelpter.AddLog("重新访问一个页面,以唤醒服务");//地址最好是全路徑,帶有http://開頭的,參考:http://localhost:8087/string strUrl = System.Configuration.ConfigurationManager.AppSettings["SelfAddress"];//本程序部署地址 try{System.Net.WebClient wc = new System.Net.WebClient();System.IO.Stream stream = wc.OpenRead(strUrl);System.IO.StreamReader reader= new System.IO.StreamReader(stream);string html = reader.ReadToEnd();//LogHelpter.AddLog("訪問的頁面" + html);if (!string.IsNullOrWhiteSpace(html)){LogHelpter.AddLog("喚醒程序成功");}reader.Close();reader.Dispose();stream.Close();stream.Dispose();wc.Dispose();}catch (Exception ex){LogHelpter.AddLog("喚醒異常" + ex.Message);} }}
这篇关于ASP.NET MVC中使用FluentScheduler任務定時器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!