Hangfire for background tasks

Are you ready?

what it is

Incredibly easy way to perform fire-and-forget, delayed and recurring tasks inside ASP.NET applications. No Windows Service required. Easy to setup, easy to configure.

Hang     fire

Pendure

Espere

Fogo

Dispare

Pendure dispare

Really easy?

// Fire and forget tasks
BackgroundJob.Enqueue( () => Console.WriteLine("Simple!") );
// Delayed tasks
BackgroundJob.Schedule( () => Console.WriteLine("Reliable!"), TimeSpan.FromDays(7) );
// Recurring tasks
RecurringJob.AddOrUpdate( () => Console.WriteLine("Transparent!"), Cron.Daily);

Yes, pretty easy!

string comprising fields separated by white space that represents a set of times.

at 9:15am Fridays in every month.

And more...

[AutomaticRetry(100, Attempts = 10]
public static void GenerateStatistics() { }

BackgroundJob.Enqueue(() => GenerateStatistics());
[Queue("critical")]
public void SomeMethod() { }

BackgroundJob.Enqueue(() => SomeMethod());

If fail, try again after 100ms

Queue in

critical list

ok, and the performance?

  • Scalable  - Use multiple server instances

  • MSMQ or Redis to reduce the processing latency to minimum.

  • Degree of parallelism

app.UseHangfire(config => {
            config.UseSqlServerStorage("cn-name");
	    //OR: 
            // config.UseRedisStorage("127.0.0.1:6379", 0, 
            //     new RedisStorageOptions{ ConnectionPoolSize = 90 });
	    config.UseServer(5, "critical", "default");
	});

aham beautiful....  

and how to test it?

public class HomeController : Controller
{
    public ActionResult Create(Comment comment)
    {
        ...
        BackgroundJob.Enqueue(() => CheckForSpam(comment.Id));
        ...
    }
}

Simple, mock it!

[TestMethod]
public void CheckForSpamJob_ShouldBeEnqueued()
{
    // Arrange
    var client = new Mock<IBackgroundJobClient>();
    var controller = new HomeController(client.Object);
    var comment = CreateComment();

    // Act
    controller.Create(comment);

    // Assert
    client.Verify(x => x.Create(
        It.Is<Job>(job => job.Method.Name == "CheckForSpam" && job.Arguments[0] == comment.Id),
        It.IsAny<EnqueuedState>());
}
public class HomeController(IBackgroundJobClient jobClient) : Controller
{
    public IBackgroundJobClient JobClient{ get; } = jobClient;

    public ActionResult Create(Comment comment)
    {
        ...
        _jobClient.Enqueue(() => CheckForSpam(comment.Id));
        ...
    }
}

View queues, stats, monitor and more with ...

... dashboard

... is open source!!

and ...

Ok, let me see code ...

Questions...

... thanks

Hangfire for background tasks

By ridermanb

Hangfire for background tasks

  • 2,456