Last active
February 16, 2023 08:28
-
-
Save ragnarstolsmark/314c34702a31855997ff570b220de420 to your computer and use it in GitHub Desktop.
Recurring job culture capture on schedule time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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