Erick
Erick

Reputation: 119

Using C#, how to clear a running application Cache to adopt timezone change?

Description

I have 2 running applications:

  1. A C# based app I created to check if time or timezone was changed and sync the time with a device. (APP1)
  2. An external/third party application that watches time to do data processing, as well as perform necessary task at a set time.(APP2)

There is also another app that checks timezone data from a Master Clock and executes on a fixed schedule. This app updates the timezone whenever the Master Clock sends a timezone update command.

I have configured APP1 to clear it's own cache so that it would get the correct time (as asked here by GregK). APP1 is working correctly.

Problem

So when the timezone has changed, APP2 execute it's scheduled tasks with delay because it is getting incorrect time.

Question

Is there a way to clear APP2's cache or force it to adopt with the timezone change without restarting it?

Upvotes: 1

Views: 1046

Answers (1)

Erick
Erick

Reputation: 119

Here's the solution I have made.

APP1 will handle the time change. It will store the current timezone the server is in. And then when when the timezone changes, it will store the time into a variable then restore the last timezone used and update the current time using the new time stored in variable. That way, the server could adopt with the time change even though the timezone will not change.

Here's how to get the correct time after a timezone change.

protected override void OnClosed ( EventArgs e )
{
   base.OnClosed(e);
   SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
}

protected override void OnLoad ( EventArgs e )
{
   base.OnLoad(e);
   SystemEvents.TimeChanged += SystemEvents_TimeChanged;
}

void SystemEvents_TimeChanged ( object sender, EventArgs e )
{
   TimeZoneInfo.ClearCachedData();
}

private void timer1_Tick ( object sender, EventArgs e )
{
   label1.Text = DateTime.Now.ToString();
}

Another reference for getting the current timezone.

TimeZone localZone = TimeZone.CurrentTimeZone;
Console.WriteLine(localZone.StandardName);

That way, you don't need to restart the application. Cheers!

Upvotes: 1

Related Questions