MVC中集成Hangfire定时任务
生活随笔
收集整理的這篇文章主要介紹了
MVC中集成Hangfire定时任务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是HangfireHangfire?
一個開源的.NET任務調度框架,目前1.6+版本已支持.NET Core。個人認為它最大特點在于內置提供集成化的控制臺,方便后臺查看及監控,如下圖:
Jucheap3.0中用到的技術
Hangfire
Hangfire.SqlServer
Hangfire.SimpleInjector
Hangfire.Console
在使用Hangfire的時候需要注意一點,Hangfire的Cron表達式暫時只支持到分鐘級別的循環任務。
本實例中,主要用了3個定時任務來做demo
1.定時發送帶附件的郵件
2.定時抓取指定幾個網站的代理ip信息,并存放到本地數據庫
3.定時驗證抓取到的代理ip地址,是否有效
基本配置代碼如下:
using System; using System.Linq; using System.Reflection; using Hangfire; using Hangfire.Console; using Hangfire.SimpleInjector; using Hangfire.SqlServer; using JuCheap.Interfaces.Task; using Owin; using SimpleInjector.Extensions.ExecutionContextScoping;namespace JuCheap.Web {public partial class Startup{/// <summary>/// 配置Hangfire/// </summary>/// <param name="app"></param>public void ConfigureHangfire(IAppBuilder app){JobIocConfig.Register();//Hangfire IOC配置GlobalConfiguration.Configuration.UseActivator(new SimpleInjectorJobActivator(JobIocConfig.Container));//hangfire 配置//使用SQLServer作為 數據庫存儲var storage = new SqlServerStorage("JuCheap-Job");GlobalConfiguration.Configuration.UseStorage(storage).UseConsole();GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });//OWIN-based authenticationvar options = new DashboardOptions{Authorization = new[]{new HangfireAuthorizationFilter()}};app.UseHangfireDashboard("/taskcenter", options);LoadRecurringTasks();var jobOptions = new BackgroundJobServerOptions{ServerName = Environment.MachineName};app.UseHangfireServer(jobOptions);}/// <summary>/// 加載Job/// </summary>public static void LoadRecurringTasks(){using (JobIocConfig.Container.BeginExecutionContextScope()){var types = from type in Assembly.Load("JuCheap.Services").GetTypes()wheretype.Namespace?.StartsWith("JuCheap.Services.TaskServices") == true &&type.GetInterfaces().Any(t => t == typeof(IRecurringTask))select type;foreach (var type in types){var task = JobActivator.Current.ActivateJob(type) as IRecurringTask;if (task == null){continue;}if (task.Enable){RecurringJob.AddOrUpdate(task.JobId, () => task.Excute(null), task.CronExpression, timeZone: TimeZoneInfo.Local);}else{RecurringJob.RemoveIfExists(task.JobId);}}}}} }
效果查看地址:http://www.jucheap.com/taskcenter
總結
以上是生活随笔為你收集整理的MVC中集成Hangfire定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: systemd服务详解
- 下一篇: QTableWidget 设置表头颜色