Skip to content

Instantly share code, notes, and snippets.

@ragnarstolsmark
Last active February 16, 2023 08:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ragnarstolsmark/314c34702a31855997ff570b220de420 to your computer and use it in GitHub Desktop.
Save ragnarstolsmark/314c34702a31855997ff570b220de420 to your computer and use it in GitHub Desktop.
Recurring job culture capture on schedule time
using Hangfire.Client;
using Hangfire.Common;
using System;
using System.Globalization;
using System.Linq;
namespace CustomGist.Hangfire
{
public class RecurringJobCaptureCultureAttribute : JobFilterAttribute, IClientFilter {
public RecurringJobCaptureCultureAttribute() {
//Set this to more than -1 to ensure it executes after the standard capture culture attribute in Hangfire
Order = 0;
}
public void OnCreated(CreatedContext filterContext) {
}
public void OnCreating(CreatingContext filterContext) {
if (filterContext == null) throw new ArgumentNullException(nameof(filterContext));
var cultureInfos = filterContext.Job.Args.OfType<CultureInfo>().ToList();
if(cultureInfos.Count < 2) {
throw new Exception("Recurring job missing culture information");
}
filterContext.SetJobParameter(
"CurrentCulture", cultureInfos[0].Name);
filterContext.SetJobParameter(
"CurrentUICulture", cultureInfos[1].Name);
}
}
}
using Hangfire;
using Hangfire.Server;
using System;
using System.Globalization;
namespace CustomGist.Hangfire
{
public class SomeRecurringJob {
[RecurringJobCaptureCulture]
public void Execute(IJobCancellationToken cancellationToken, PerformContext context, CultureInfo culture, CultureInfo uICulture) {
//Write your code here that will now execute in the given culture, the culture and uICulture arguments can be ignored
}
public static void Schedule(){
var culture = new CultureInfo("nb-NO");
RecurringJob.AddOrUpdate<SomeRecurringJob>("somerecurringjobid", x => x.Execute(cancellationToken: JobCancellationToken.Null, context: null, culture: culture, uICulture: culture), Cron.Daily, TimeZoneInfo.Local);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment