已将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!";
}