I have a method that I want to run in the background called GenerateDocument. I only want this to try to run for xx seconds before giving up. Is there a way to do this with Hangfire?
so in my method declaration I would have:
public int GenerateDocument(IDocumentSettings settings)
//my method stuffs here
Is there something that I can specify that i only want it to run for so many seconds and then have the CancellationToken throw an exception?
Did you find a solution for this?
Still looking for an answer to this question.
There’s no way to terminate the job without terminating the entire worker thread. But you can construct your own cancellation token which would cancel after specified time:
public async Task GenerateDocument(CancellationToken cancellationToken)
var timeout = TimeSpan.FromSeconds(10);
using (var timeoutTokenSource = new CancellationTokenSource(timeout))
using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutTokenSource.Token))
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
// ignore OperationCanceledException if terminated because of timeout