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

已将SchedulePollingInterval 设为1,按分重复执行任务时仍不能精确到按秒执行

已将SchedulePollingInterval 设为1,按分重复执行任务时仍不能精确到按秒执行(如12:30:00执行一次,下一次应该是12:31:00,实际要么快几秒,要么慢20几秒)


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",
       })));
 
   builder.Services.AddHangfireServer(options =>
  {
      options.ServerName = "task";
      options.SchedulePollingInterval = TimeSpan.FromSeconds(1);
      options.WorkerCount = 15;//并行数
  });
 
 
        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()
    {      
              RecurringJob.AddOrUpdate<MyJob>(x => x.MyMethod(), Cron.MinuteInterval(1));
              //RecurringJob.AddOrUpdate<MyJob>(x=>x.MyMethod(), "0 */1 * * * ?");//每1分一次
        return View();
    }


    public class MyJob
    {
        public string MyMethod()
        {
            Console.WriteLine("execute method!"+DateTime.Now);
            // 后台任务逻辑
            return "Hello, World!";
        }
  • 写回答

2条回答 默认 最新

  • 软件技术NINI 2024-10-10 10:46
    关注
    
    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),
               JobExpirationCheckInterval = TimeSpan.FromMinutes(20),
               CountersAggregateInterval = TimeSpan.FromMinutes(5),
               PrepareSchemaIfNecessary = true,
               DashboardJobListLimit = 50000,
               TransactionTimeout = TimeSpan.FromMinutes(1),
               TablesPrefix = "Hangfire",
           })));
     
            builder.Services.AddHangfireServer(options =>
            {
                options.ServerName = "task";
                options.SchedulePollingInterval = TimeSpan.FromSeconds(1);
                options.WorkerCount = 15;
            });
     
            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()
    {      
        RecurringJob.AddOrUpdate<MyJob>(x => x.MyMethod(), Cron.MinuteInterval(1));
        //RecurringJob.AddOrUpdate<MyJob>(x=>x.MyMethod(), "0 */1 * * * ?");//每1分一次
        return View();
    }
     
    public class MyJob
    {
        public string MyMethod()
        {
            DateTime startTime = DateTime.Now;
            Console.WriteLine("execute method! Start Time: " + startTime);
            
            // 后台任务逻辑
            
            DateTime endTime = DateTime.Now;
            Console.WriteLine("execute method! End Time: " + endTime);
            
            TimeSpan executionTime = endTime - startTime;
            Console.WriteLine("Execution Time: " + executionTime.TotalSeconds + " seconds");
            
            return "Hello, World!";
        }
    }
     
     
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月19日
  • 已采纳回答 10月11日
  • 修改了问题 10月10日
  • 创建了问题 10月10日

悬赏问题

  • ¥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