I’m trying to determine if I can use Hangfire to schedule tasks sequentially (one at a time) in a console application.
Below is my test application and the output. It attempts to run tasks at 1, 2, 3, 4, and 5-minute intervals.
But the output make no sense at all. Note that the output always shows 0 minutes have elapsed because my Tasks
constructor is being called multiple times. It should only be called once. (I tried moving the call to the constructor to before the using statement, but still got the same results!
I’m lost. None of this makes any sense to me. Can someone help me out?
Code
var options = new BackgroundJobServerOptions
{
WorkerCount = 1,
};
GlobalConfiguration.Configuration
.UseMemoryStorage();
//UseSqlServerStorage("connection_string");
using (var server = new BackgroundJobServer(options))
{
Tasks 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 Tasks
{
public DateTime StartTime { get; private set; }
public Tasks()
{
StartTime = DateTime.Now;
}
public void RunTask(int interval)
{
Console.WriteLine($"{interval} : Start {(int)Math.Round((DateTime.Now - StartTime).TotalMinutes)} minutes");
Thread.Sleep(2000);
Console.WriteLine($"{interval} : End");
}
}
Output
Hangfire Server started. Press any key to exit...
Start: 8/1/2023 1:43 PM
4 : Start 0 minutes
4 : End
2 : Start 0 minutes
2 : End
1 : Start 0 minutes
1 : End
5 : Start 0 minutes
5 : End
3 : Start 0 minutes
3 : End
1 : Start 0 minutes
1 : End