图片

快点关注我们吧

图片

作者介绍


翁薪钧,现就职于华东院,前端开发。从事过winform,上位机开发,wms开发。疫情期间接触wtm框架,先后使用了layui,vue版本。使用wtm框架,主要是看重了代码生成器,权限分配,用户管理,数据库操作等功能。之前苦于没有一个好的框架,一直都是手写代码,效率低下,重复劳动。现在用wtm,crud基础的代码都是生成,自己专注于业务逻辑,效率提高,bug减少了很多。也是接触了wtm,自己也开始学习.net core,从.net core2.2一直到现在.net 5.0,跟着wtm一同进步了很多。




定时任务选用Hangfire主要是看中他自带面板功能。

  1. 在model引入 Hangfire Hangfire.SQLite


    图片

  2. 在startup.cs 文件
    public void ConfigureServices(IServiceCollection services)

var sqliteOptions = new SQLiteStorageOptions();
SQLitePCL.Batteries.Init();
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseLogProvider(new ColouredConsoleLogProvider())
.UseSQLiteStorage("Data Source=./wg.db;", sqliteOptions) );

图片

3.在 public void Configure(IApplicationBuilder app, IOptionsMonitor configs, IHostEnvironment env)

var option = new BackgroundJobServerOptions {
WorkerCount = 1 };
app.UseHangfireServer(option);
app.UseDeveloperExceptionPage();
app.UseHangfireDashboard("/hangfire",
new Hangfire.DashboardOptions {
Authorization = new[] {
new MyDashboardAuthorizationFilter()
}
});
RecurringJob.AddOrUpdate<WeatherJobService>("获取天气数据", p => p.GetWeatherInfo(), Cron.Daily(8));

图片

  1. 写 MyDashboardAuthorizationFilter

`
using Hangfire.Annotations;
using Hangfire.Dashboard;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace zoecloud.JobService
{
public class MyDashboardAuthorizationFilter : IDashboardAuthorizationFilter
{

   public bool Authorize([NotNull] DashboardContext context)
{

var httpContext = context.GetHttpContext();

var header = httpContext.Request.Headers["Authorization"];

if (string.IsNullOrWhiteSpace(header))
{
SetChallengeResponse(httpContext);
return false;
}

var authValues = System.Net.Http.Headers.AuthenticationHeaderValue.Parse(header);

if (!"Basic".Equals(authValues.Scheme, StringComparison.InvariantCultureIgnoreCase))
{
SetChallengeResponse(httpContext);
return false;
}

var parameter = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authValues.Parameter));
var parts = parameter.Split(':');

if (parts.Length < 2)
{
SetChallengeResponse(httpContext);
return false;
}

var username = parts[0];
var password = parts[1];

if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
SetChallengeResponse(httpContext);
return false;
}

if (username == "admin" && password == "123456")
{
return true;
}

SetChallengeResponse(httpContext);
return false;
}

private void SetChallengeResponse(HttpContext httpContext)
{
httpContext.Response.StatusCode = 401;
httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\\"Hangfire Dashboard\\"");
httpContext.Response.WriteAsync("Authentication is required.");
}
}

}
`
图片

  1. 写自己的服务

`

public class WeatherJobService

{

CS connection;
Logger logger;
ILedServer ledServer;


public WeatherJobService(IServiceScopeFactory serviceScopeFactory)
{
logger = LogManager.GetCurrentClassLogger();
var wtmContext = serviceScopeFactory.CreateScope().ServiceProvider.GetRequiredService<WTMContext>();
connection = wtmContext.ConfigInfo.Connections[0];
ledServer = serviceScopeFactory.CreateScope().ServiceProvider.GetRequiredService<ILedServer>();
}

//[Hangfire.Queue("get_weather")]
public void GetWeatherInfo()
{
try
{
using (var udc = connection.CreateDC())
{
var restclient = new RestClient("http://wthrcdn.etouch.cn/WeatherApi");
var orgList = udc.Set<Organization>().ToList();
for (int i = 0; i < orgList.Count; i++)
{
if (!string.IsNullOrEmpty(orgList[i].WeatherCity))
{
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.Timeout = 5000;
request.AddParameter("city", orgList[i].WeatherCity);

var response = restclient.Execute(request);
var content = response.Content;
logger.Info($"组织名称,{orgList[i].Name},{content}");
orgList[i].StrWeather = JsonConvert.SerializeObject(XmlHelper.XmlDeSeralizer<resp>(content));
udc.Set<Organization>().Update(orgList[i]);
}
}
udc.SaveChanges();
ledServer.SendWeatherInfo(null);
}
}
catch (Exception ex)
{
logger.Info(ex.Message);
}
}
}`

图片

  1. 调用自己的服务

图片

  1. 后端面板链接

xxx:端口/hangfire

图片

  1. 面板可以手动触发自己写的定时任务,可以把面板作为外部链接添加到wtm菜单里面

图片

  1. HangFire官网文档链接

https://www.hangfire.io/


来源:https://mp.weixin.qq.com/s/_OD9CMyHiGjgnRL34ct6Ww
点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部