asp.net使用Hangfire开发后台定时任务demo

时间:2022-09-04 17:23:35

一、新建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 }

);

}
}
}

调用:
http://localhost:45296/api/Message/Post/testMessage

查看任务:
http://your-site/hangfire