Hangfire: Calling methods with delay doesn't work

Viewed 1652

I have an ASP.NET core application and wanted to use Hangfire for some background tasks. I set up Hangfire as it was described in the official documentation, and I can call usual background tasks. However, I have problems with calling the methods with delay.

public void Configure(/*other params*/ IBackgroundJobClient backgroundJobsClient)
{
   //Other code
   
   backgroundJobsClient.Enqueue(() => Console.WriteLine("Method"));
   backgroundJobsClient.Schedule(() => Console.WriteLine("Delayed Method"), TimeSpan.FromSeconds(2));
}

I have only "Method" output in the console.

After waiting for a minute, I have an exception in my console:

Hangfire.Processing.BackgroundExecution[0] Execution DelayedJobScheduler is in the Failed state now due to an exception, execution will be retried no more than in 00:00:04 Hangfire.PostgreSql.PostgreSqlDistributedLockException: Could not place a lock on the resource 'HangFire:locks:schedulepoller': Lock timeout. at Hangfire.PostgreSql.PostgreSqlDistributedLock.PostgreSqlDistributedLock_Init_Transaction(String resource, TimeSpan timeout, IDbConnection connection, PostgreSqlStorageOptions options) at Hangfire.PostgreSql.PostgreSqlDistributedLock..ctor(String resource, TimeSpan timeout, IDbConnection connection, PostgreSqlStorageOptions options) at Hangfire.PostgreSql.PostgreSqlConnection.AcquireDistributedLock(String resource, TimeSpan timeout) at Hangfire.Server.DelayedJobScheduler.UseConnectionDistributedLock[T](JobStorage storage, Func2 action) at Hangfire.Server.DelayedJobScheduler.EnqueueNextScheduledJobs(BackgroundProcessContext context) at Hangfire.Server.DelayedJobScheduler.Execute(BackgroundProcessContext context) at Hangfire.Server.BackgroundProcessDispatcherBuilder.ExecuteProcess(Guid executionId, Object state) at Hangfire.Processing.BackgroundExecution.Run(Action2 callback, Object state) !!! Could not place a lock on the resource 'HangFire:locks:schedulepoller': Lock timeout.

So, I suppose there is some issue with delayed methods initialization. Could someone help me with that? Probably I didn't setup Hangfire correctly for ASP.NET core.

2 Answers

I've finally found a solution. The date stores in the Hangfire database in UTC format. I didn't know that, and official documentation doesn't say anything about that. The correct code should look something like this:

DateTime.UtcNow.AddSeconds(2);

I resolved this problem as below.

There is lock table in the Hangfire tables. I deleted all data in the lock table, my issue solved.

Related