定时任务选用Hangfire主要是看中他自带面板功能。
-
在model引入 Hangfire Hangfire.SQLite
-
在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
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));
- 写 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.");
}
}
}
`
- 写自己的服务
`
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);
}
}
}`
- 调用自己的服务
- 后端面板链接
xxx:端口/hangfire
- 面板可以手动触发自己写的定时任务,可以把面板作为外部链接添加到wtm菜单里面
- 官网文档链接