MVC中集成Hangfire定时任务
生活随笔
收集整理的這篇文章主要介紹了
MVC中集成Hangfire定时任务
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
什么是HangfireHangfire?
一個(gè)開(kāi)源的.NET任務(wù)調(diào)度框架,目前1.6+版本已支持.NET Core。個(gè)人認(rèn)為它最大特點(diǎn)在于內(nèi)置提供集成化的控制臺(tái),方便后臺(tái)查看及監(jiān)控,如下圖:
Jucheap3.0中用到的技術(shù)
Hangfire
Hangfire.SqlServer
Hangfire.SimpleInjector
Hangfire.Console
在使用Hangfire的時(shí)候需要注意一點(diǎn),Hangfire的Cron表達(dá)式暫時(shí)只支持到分鐘級(jí)別的循環(huán)任務(wù)。
本實(shí)例中,主要用了3個(gè)定時(shí)任務(wù)來(lái)做demo
1.定時(shí)發(fā)送帶附件的郵件
2.定時(shí)抓取指定幾個(gè)網(wǎng)站的代理ip信息,并存放到本地?cái)?shù)據(jù)庫(kù)
3.定時(shí)驗(yàn)證抓取到的代理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作為 數(shù)據(jù)庫(kù)存儲(chǔ)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
總結(jié)
以上是生活随笔為你收集整理的MVC中集成Hangfire定时任务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: systemd服务详解
- 下一篇: s3c2440移植MQTT