asp.net使用Hangfire開發後臺定時任務demo
阿新 • • 發佈:2018-12-27
一、新建webapi專案
WebApplicationWebApiHangfireSample
在根目錄新增Startup.cs檔案
using Hangfire;
using Hangfire.MemoryStorage;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApplicationWebApiHangfireSample.Startup))]
namespace WebApplicationWebApiHangfireSample
{
/// <summary>
/// 演示Hangfire的配置
/// </summary>
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
//指定Hangfire使用記憶體儲存後臺任務資訊
GlobalConfiguration.Configuration.UseMemoryStorage();
//啟用HangfireServer這個中介軟體(它會自動釋放)
app.UseHangfireServer();
//啟用Hangfire的儀表盤(可以看到任務的狀態,進度等資訊)
app.UseHangfireDashboard();
}
}
}
在controls資料夾中新建檔案MessageController.cs
using Hangfire;
using System;
using System.Diagnostics;
using System.Web.Http;
namespace WebApplicationWebApiHangfireSample.Controllers
{
/// <summary>
/// 用來公開給前端使用者呼叫的API
/// </summary>
public class MessageController : ApiController
{
/// <summary>
/// 這個是用來發送訊息的靜態方法
/// </summary>
/// <param name="message"></param>
public static void Send(string message)
{
EventLog.WriteEntry("EventSystem", string.Format("這是由Hangfire後臺任務傳送的訊息:{0},時間為:{1}", message, DateTime.Now));
}
public IHttpActionResult Post(string content)
{
//這裡可以做一些業務判斷或操作
//然後需要推送的時候,呼叫下面的方法即可
BackgroundJob.Enqueue(() => Send(content));
//最後返回(這裡是立即返回,不會阻塞)
return Ok();
}
}
}
修改App_Start資料夾下的WebApiConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace WebApplicationWebApiHangfireSample
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi2",
routeTemplate: "api/{controller}/{action}/{content}",
defaults: new {ApiController="Message",Action="Post", content = RouteParameter.Optional }
);
}
}
}