I've this code in my ASP.NET MVC
application to share a value across the application.
public static class Global
{
public static string Token { get; private set; };
public static void LoadFromFile()
{
// loads Token value from a settings file
}
}
What I want to do is to run LoadFromFile
method once a day to update the Token
value.
I can't use a separate background task like in HangFire
, since I want to update the value for current running application.
How can I do it? thanks.
Update: Mates who think this is a duplicate, please read the question. I want to update the shared value in current running application. changing it in in a separate background task won't change it for current application.
To help SO wandering polices rest a while, I got the answer.
I can run a scheduled background task to access an endpoint in my site, and from there update the static Token
value.
I had faced similar requirement once, here is the trick I used
private static DateTime lastRunAt;
private static object loadingTokenLock = new object();
private static bool TokenUpdateNeeded
{
get
{
return DateTime.UtcNow.DayOfYear != lastRunAt.DayOfYear;
}
}
public static void TryLoadToken()
{
if (TokenUpdateNeeded)
lock (loadingTokenLock)
if (TokenUpdateNeeded)
LoadFromFile();
}
public static void LoadFromFile()
{
// loads Token value from a settings file
lastRunAt = DateTime.UtcNow;
}
void Session_Start(object sender, EventArgs e)
{
TryLoadToken();
}
I can't remember the exact coding, but the idea was to update the Token upon the first request of the day.
The problem is if your application have not been visit for more than a day, the Token will not be updated. So we defined a task in Windows Task Scheduler to visit the site once everyday
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.