WTM整合HangFire


定時任務選用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菜單里面

image

  1. 官網文檔鏈接

https://www.hangfire.io/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM