If you are using Hangfire in your .NET Core application and encounter the “Timeout expired” error when executing long-running tasks, don’t worry. This blog post will guide you through the steps to increase the Hangfire job timeout and prevent job failures due to timeout issues.
Understanding the Timeout Expired Error
The “Timeout expired” error occurs when a job execution exceeds the defined timeout period, resulting in job termination. In Hangfire, this error can occur when executing SQL stored procedures that take a significant amount of time to complete.
Solution: Increasing SQLCommand Timeout
To resolve the “Timeout expired” error, you need to increase the SQLCommand timeout. By default, the timeout is set to 30 seconds, which may not be sufficient for long-running tasks. Here’s an example of how to increase the timeout:
code
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 3600; // Set the timeout to 1 hour
await cmd.ExecuteNonQueryAsync();
}
By setting the CommandTimeout
property to a longer duration, such as 3600 seconds (1 hour), you allow sufficient time for the stored procedure to complete without timing out.
Configuring Hangfire Settings
In addition to increasing the SQLCommand timeout, you can configure Hangfire settings to ensure that jobs have enough time to execute. Here’s an example of configuring Hangfire settings in your .NET Core application:
code
services.AddHangfire(configuration =>
configuration.UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"),
new SqlServerStorageOptions
{
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(30),
QueuePollInterval = TimeSpan.Zero,
UsePageLocksOnDequeue = false,
DisableGlobalLocks = false
}));
By adjusting the SlidingInvisibilityTimeout
and other options, you can fine-tune the Hangfire job execution and prevent premature timeouts.
Testing and Optimization
After implementing the above solutions, it’s essential to test your Hangfire jobs and monitor their execution time. Observe the behavior of long-running tasks and optimize their performance if necessary. You can review the job execution time, analyze bottlenecks, and make adjustments to improve overall job reliability and efficiency.
Conclusion
By increasing the SQLCommand timeout and configuring Hangfire settings, you can prevent the “Timeout expired” error and ensure successful execution of long-running tasks in your .NET Core application. Remember to adjust the CommandTimeout
property when executing SQL stored procedures and fine-tune Hangfire settings according to your specific requirements. By implementing these solutions and monitoring job execution, you can optimize your Hangfire job performance and reliability.
If you have any questions or encountered other Hangfire-related issues, feel free to leave a comment below. Happy coding and enjoy the seamless execution of your Hangfire jobs.