hangfire

How to handle Fire and Forget Job on server side?


I am not sure, if I am understanding Hangifre correctly.

So I have my Client and it is sending this to the server:

var testModel = new CreateModel();
testModel.App = "example.com/";
testModel.Name = "testname.zip";

var jobId = BackgroundJob.Enqueue(() => JsonConvert.SerializeObject(testModel));

So this is working fine, the job is created and together with the Json testModel argument in the database.

Now I need to do something with the testModel on the serverside. The server is running correctly, but how can I achieve it, that i get the job and do something with it on the server? The database says that the task Succeeded, but yeah I could not fetch it on the server side. I need to work with the data on the Hangfire Server.

I cannot find it in the hangifre documentation.


Solution

  • Background jobs in Hangfire are like Azure Functions (https://azure.microsoft.com/en-us/products/functions) or Amazon Lambda (https://aws.amazon.com/lambda/) - the thing you enqueue needs to be some self-contained task. Think of it as a method that's executed at some arbitrary time in the future.

    So you probably want something like

    public class DownloadFileJob
    {
        public async Task ExecuteAsync(string url, string fileName, PerformContext context, CancellationToken token)
        {
            // do whatever you're trying to do with the URL and file name
        }
    }
    

    And you'd enqueue it like so (no need for that model in your question):

    var jobId = BackgroundJob.Enqueue<DownloadFileJob>(m => m.ExecuteAsync(url, fileName, null, CancellationToken.None);
    

    The job is serialized when enqueued, then deserialized into a DownloadFileJob object when Hangfire processes the job, which in this case will execute that object's ExecuteAsync() method using the provided arguments.