I’ve written a small test application to get a feel for Hangfire. But the results are not at all what I was expecting.
Here’s the code.
GlobalConfiguration.Configuration
.UseMemoryStorage();
using var server = new BackgroundJobServer();
TaskExecutor tasks = new();
Console.WriteLine("Hangfire Server started. Press any key to exit...");
Console.WriteLine($"Start: {tasks.StartTime:g}");
RecurringJob.AddOrUpdate("1", () => tasks.RunTask(1), "*/1 * * * *");
RecurringJob.AddOrUpdate("2", () => tasks.RunTask(2), "*/2 * * * *");
RecurringJob.AddOrUpdate("3", () => tasks.RunTask(3), "*/3 * * * *");
RecurringJob.AddOrUpdate("4", () => tasks.RunTask(4), "*/4 * * * *");
RecurringJob.AddOrUpdate("5", () => tasks.RunTask(5), "*/5 * * * *");
Console.ReadKey();
class TaskExecutor
{
public DateTime StartTime { get; private set; }
public TaskExecutor()
{
StartTime = DateTime.Now;
}
[DisableConcurrentExecution(30 * 60)]
public void RunTask(int interval)
{
Console.WriteLine($"{interval} : Start {Math.Round((DateTime.Now - StartTime).TotalMinutes):#,0.##} minutes");
Thread.Sleep(2000);
Console.WriteLine($"{interval} : End");
}
}
Here’s the output I’m expecting.
1 : Start 1 minutes
1 : End
1 : Start 2 minutes
1 : End
2 : Start 2 minutes
2 : End
1 : Start 3 minutes
1 : End
3 : Start 3 minutes
3 : End
1 : Start 4 minutes
1 : End
2 : Start 4 minutes
2 : End
4 : Start 4 minutes
4 : End
1 : Start 5 minutes
1 : End
5 : Start 5 minutes
5 : End
Instead, here’s the actual output.
1 : Start 0 minutes
1 : End
3 : Start 0 minutes
3 : End
2 : Start 0 minutes
2 : End
1 : Start 0 minutes
1 : End
5 : Start 0 minutes
5 : End
1 : Start 0 minutes
1 : End
4 : Start 0 minutes
4 : End
3 : Start 0 minutes
3 : End
2 : Start 0 minutes
2 : End
1 : Start 0 minutes
1 : End
The order and timing make no sense to me. And my number of minutes elapsed remains at zero. Debugging the code, it appears the reason the elapsed time doesn’t change is because my TaskExecutor
is being recreated. This too is completely unexpected. Why would there be more than one instance of this class?
Can anyone help me make sense of this?