stevenjin 2024-10-09 10:25 采纳率: 98%
浏览 4
已结题

hangfire 定时任务入队列但不执行

1.NET 7.0 ASP.NET CORE MVC
2.运行后,控制台没有打印出信息,在面板中有入队,但没有执行成功信息

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        
        // Add services to the container.
        builder.Services.AddControllersWithViews();
        builder.Services.AddHangfire(configuration => configuration
       .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)//此方法 只初次创建数据库使用即可
       .UseSimpleAssemblyNameTypeSerializer()
       .UseRecommendedSerializerSettings()
       .UseStorage(new MySqlStorage("Server=127.0.0.1;uid=root;pwd=123;database=JobDB;AllowLoadLocalInfile=true;Allow User Variables=True", new MySqlStorageOptions
       {
           TransactionIsolationLevel = (System.Transactions.IsolationLevel?)System.Data.IsolationLevel.ReadCommitted, //事务隔离级别。默认是读取已提交
           QueuePollInterval = TimeSpan.FromSeconds(1), //- 作业队列轮询间隔。默认值为15秒。
           JobExpirationCheckInterval = TimeSpan.FromMinutes(20),
           CountersAggregateInterval = TimeSpan.FromMinutes(5),
           PrepareSchemaIfNecessary = true, // 如果设置为true,则创建数据库表。默认是true
           DashboardJobListLimit = 50000,
           TransactionTimeout = TimeSpan.FromMinutes(1),
           TablesPrefix = "Hangfire",
       })));




        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

        app.UseRouting();      


        app.UseHangfireDashboard();
      

        app.UseAuthorization();

        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        app.Run();
    }
}

    public IActionResult Index()
    {      
        //支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。
        var jobId = BackgroundJob.Enqueue(() => WriteLog("队列任务"));
        return View();
    }
  • 写回答

2条回答 默认 最新

  • 清水白石008 2024-10-09 10:29
    关注
    ??上午好,题主!目前:??[在线]
    ??参考GPT-4o mini 模型、由清水白石008整理提供!
    ??今日金句:“苦难是人生的老师,通过苦难,走向欢乐。” —— 贝多芬
    

    在使用 Hangfire 进行定时任务调度时,如果任务入队但没有执行,可能有几个原因。以下是一些常见的问题及其解决方案:

    1. 确保 Hangfire 服务器已启动

    Hangfire 需要一个后台处理程序来执行入队的任务。你需要在应用程序中启动 Hangfire 服务器。可以在 Program.cs 中添加以下代码:

    app.UseHangfireServer();
    

    确保这行代码在 app.UseHangfireDashboard(); 之前。

    2. 检查数据库连接

    确保你的 MySQL 数据库连接字符串正确,并且数据库服务正在运行。你可以尝试直接连接到数据库以验证连接字符串的有效性。

    3. 检查任务执行的日志

    Hangfire 提供了一个仪表板,可以查看任务的状态和日志。确保你访问了 Hangfire 的仪表板(通常是 /hangfire),查看任务的状态和任何可能的错误信息。

    4. 确保任务方法是可访问的

    确保 WriteLog 方法是 public 的,并且没有参数。Hangfire 只能调度无参数的公共方法。

    public void WriteLog(string message)
    {
        // 这里可以添加日志记录逻辑
        Console.WriteLine(message);
    }
    

    5. 检查 Hangfire 的配置

    确保 Hangfire 的配置没有问题。你可以尝试使用默认的 SQL Server 存储来排除 MySQL 存储的问题。

    6. 处理异常

    如果任务执行时抛出异常,Hangfire 会将其标记为失败。确保在 WriteLog 方法中处理可能的异常,并查看 Hangfire 的仪表板以获取详细的错误信息。

    7. 任务过期

    如果任务在入队后没有被处理,可能是因为任务过期。确保 JobExpirationCheckInterval 和其他相关设置符合你的需求。

    8. 运行环境

    确保你的应用程序在适当的环境中运行(例如,开发或生产),并且没有其他配置问题。

    示例代码

    以下是更新后的 Program.cs 示例代码:

    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            
            // Add services to the container.
            builder.Services.AddControllersWithViews();
            builder.Services.AddHangfire(configuration => configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseStorage(new MySqlStorage("Server=127.0.0.1;uid=root;pwd=123;database=JobDB;AllowLoadLocalInfile=true;Allow User Variables=True", new MySqlStorageOptions
                {
                    TransactionIsolationLevel = System.Data.IsolationLevel.ReadCommitted,
                    QueuePollInterval = TimeSpan.FromSeconds(1),
                    JobExpirationCheckInterval = TimeSpan.FromMinutes(20),
                    CountersAggregateInterval = TimeSpan.FromMinutes(5),
                    PrepareSchemaIfNecessary = true,
                    DashboardJobListLimit = 50000,
                    TransactionTimeout = TimeSpan.FromMinutes(1),
                    TablesPrefix = "Hangfire",
                })));
    
            var app = builder.Build();
    
            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
    
            app.UseRouting();
    
            app.UseHangfireDashboard();
            app.UseHangfireServer(); // 启动 Hangfire 服务器
    
            app.UseAuthorization();
    
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
    
            app.Run();
        }
    }
    

    总结

    通过以上步骤,你应该能够诊断并解决 Hangfire 任务入队但不执行的问题。如果问题仍然存在,请检查 Hangfire 的文档和社区支持,获取更多帮助。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月17日
  • 已采纳回答 10月9日
  • 创建了问题 10月9日

悬赏问题

  • ¥60 Matlab联合CRUISE仿真编译dll文件报错
  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId