Click here to Skip to main content
Click here to Skip to main content

Windows System Time Synchronizer

By , 24 May 2007
 

Screenshot - Article.gif

Introduction

This is a simple utility written in C# .NET Version 2.0. It synchronizes Windows system time with Yahoo! server time through a web service offered by Yahoo!.

Using the code

The utility makes an HTTP request to the Yahoo! URL, which returns Yahoo! server time as a timestamp in XML format. Then the XML is parsed to get the timestamp and is converted into regional date-time. Windows system time is modified to this using a P-Invoke function call.

/*
 * WINDOWS TIME SYNCHRONIZER - C# .NET
 * 
 * FILE NAME    :    Program.cs
 * 
 * DATE CREATED :    March 06, 2007, 12:05:54 PM
 * CREATED BY   :    Gunasekaran Paramesh
 * 
 * LAST UPDATED :    April 25, 2007, 12:38:12 PM
 * UPDATED BY   :    Gunasekaran Paramesh
 * 
 * DESCRIPTION  :    Synchronizes Windows System Time with Yahoo! Server Time.
*/

using System;
using System.Net;
using System.Xml;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Microsoft.Win32;
using System.Configuration;
using System.Runtime.InteropServices;

namespace TryWinTimeSync
{
    class Program
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct SYSTEMTIME 
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }

        [DllImport("kernel32.dll", SetLastError=true)]
        public static extern bool SetSystemTime( [In] ref SYSTEMTIME st );

        [STAThread]
        static void Main(string[] args)
        {
            BooleanSwitch Tracer = new BooleanSwitch("TraceSwitch", 
                "Trace for entire application");
            EventLog Log = null;

            try
            {
                // Initialize EventLog
                Log = new EventLog();
                if(!System.Diagnostics.EventLog.SourceExists("WinTimeSync"))
                    System.Diagnostics.EventLog.CreateEventSource(
                        "WinTimeSync", "Zion");
                Log.Source = "WinTimeSync";
                Log.Log = "Zion";
                
                if ( Tracer.Enabled )
                    Trace.Listeners.Add(new EventLogTraceListener(Log));

                Trace.WriteLineIf(Tracer.Enabled, "Starting WinTimeSync...");

                Boolean ServiceAlive = true;
                Double CurrentTimestamp = 0;

                Trace.WriteLineIf(Tracer.Enabled, 
                    "Opening configuration file for initializing" + 
                    " global settings...");

                Int32 SyncInterval = Convert.ToInt32(
                    ConfigurationSettings.AppSettings[
                    "SyncInterval"].ToString());
                String RequestURL = ConfigurationSettings.AppSettings[
                    "TimeServerURL"].ToString();

                Trace.WriteLineIf(Tracer.Enabled, 
                    "Global settings initialized [SyncInterval: " + 
                    SyncInterval + " minutes; RequestURL: " + 
                    RequestURL + "]");

                while ( ServiceAlive )
                {
                    Trace.WriteLineIf(!Tracer.Enabled, 
                    "Synchronizing system time with time server...");

                    // Send HTTP request for Timestamp
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Creating HTTP request to [" + RequestURL + "]");
                    WebRequest Req = WebRequest.Create(RequestURL);
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Setting default proxy for the HTTP request...");
                    Req.Proxy = WebProxy.GetDefaultProxy();
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Sending HTTP request...");
                    WebResponse Res = Req.GetResponse();

                    // Save as Timestamp as a temporary XML file
                    String TempFile = Guid.NewGuid().ToString() + ".xml";
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Creating a temporary XML file [" + TempFile + "]");
                    StreamWriter SW = new StreamWriter(TempFile);
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Saving HTTP response to the temporary XML file...");
                    SW.Write(new StreamReader(
                        Res.GetResponseStream()).ReadToEnd());
                    SW.Close();

                    // Read the XML file and get the Timestamp value
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Opening the temporary XML file...");
                    XmlTextReader MyXML = new XmlTextReader(TempFile);
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Reading the temporary XML file...");
                    while ( MyXML.Read() )
                    {
                        switch ( MyXML.NodeType )
                        {
                            case XmlNodeType.Element:
                            if ( MyXML.Name == "Timestamp" )
                            {
                                Trace.WriteLineIf(Tracer.Enabled, 
                                    "Retriving the current timestamp" + 
                                    " from the temporary XML file...");
                                CurrentTimestamp = Convert.ToDouble(
                                    MyXML.ReadInnerXml());
                                Trace.WriteLineIf(Tracer.Enabled, 
                                    "Current timestamp retrived [
                                    " + CurrentTimestamp + "]");
                            }
                            break;
                        }
                    }
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Closing the temporary XML file...");
                    MyXML.Close();

                    // Delete the temporary XML file
                    FileInfo TFile = new FileInfo(TempFile);
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Deleting the temporary XML file...");
                    TFile.Delete();

                    // Convert Timestamp to Time
                    DateTime MyDateTime = 
                        new DateTime(1970, 1, 1, 0, 0, 0, 0);
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Converting the timestamp to time...");
                    MyDateTime = MyDateTime.AddSeconds(CurrentTimestamp);
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Timestamp converted to time [
                        " + MyDateTime.ToLocalTime() + "]");

                    // Change the system time
                    SYSTEMTIME SysTime = new SYSTEMTIME();
                    SysTime.wYear = (short) MyDateTime.Year;
                    SysTime.wMonth = (short) MyDateTime.Month; 
                    SysTime.wDay = (short) MyDateTime.Day;
                    SysTime.wHour = (short) MyDateTime.Hour;
                    SysTime.wMinute = (short) MyDateTime.Minute;
                    SysTime.wSecond = (short) MyDateTime.Second;
                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Setting the system time...");
                    SetSystemTime(ref SysTime);

                    Trace.WriteLineIf(Tracer.Enabled, 
                        "Switching to sleep state until SyncInterval...");
                    for ( int i = 0; i < SyncInterval; i++ )
                        Thread.Sleep(1000 * 60);
                        Trace.WriteLineIf(Tracer.Enabled, 
                            "Switching back to active mode...");
                }
            }
            catch ( Exception Ex )
            {
                // Log for errors                
                if ( Tracer.Enabled )
                    Log.WriteEntry(Ex.StackTrace, EventLogEntryType.Error);
                else
                    Log.WriteEntry(Ex.Message, EventLogEntryType.Error);
            }
        }
    }
}

Sample configuration file

Below is the sample configuration file. TraceSwitch is used to enable debug log messages. SyncInterval specifies the elapsed time in seconds where the utility synchronizes the Windows system time with the Yahoo! time server. TimeServerURL specifies the actual Yahoo! URL which, on request, returns the server time.

<configuration>
    <system.diagnostics>
        <switches>
            <add name="TraceSwitch" value="1" />
        </switches>
    </system.diagnostics>
    <appSettings>
        <add key="SyncInterval" value="60" />
        <add key="TimeServerURL" value=
"http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo" />
    </appSettings>
</configuration>

History

  • Baseline v1.0 - April 25, 2007

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Paramesh Gunasekaran
Technical Lead HCL Technologies
India India
Member
Paramesh Gunasekaran is currently working as a Software Engineer in HCL Technologies, India. He obtained his Bachelor's degree in Information Technology from Anna University, India. His research areas include Computational Biology, Artificial Neural Networks and Network Engineering. He has also received international acclaim for authoring industry papers in these areas. He is a Microsoft Certified Professional in ASP.NET/C# and has also been working in .NET technologies for more than 8 years.
 
Web: http://www.paramg.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberDiptimoy12347 Dec '11 - 18:24 
not working properly
GeneralNTPmemberWael Al Wirr9 Aug '07 - 3:21 
hey guys,
I am trying to synchronize my server with a NTP server can anyone help me ?
 
WaelA
Software Engineer
WaelA@hotmail.com

Generalit visits strange adds sites ?!memberandré_k17 Jul '07 - 21:02 
perhaps the Yahoo's "web service" site you proposed systematically opens those adds:
 
Access:Outbound TCP access Object:1040 -> 66.94.228.98 (www.hackday.org):80 (http)
Access:Outbound TCP access Object:1041 -> 81.95.96.66 (uvirt1.active24.cz):80 (http)
Access:Outbound TCP access Object:1042 -> 194.154.75.194 (webhosting-bix.rbc.ru):80 (http)
Access:Outbound TCP access Object:1043 -> 72.22.69.53 (host368.ipowerweb.com):80 (http)
 
And so will be with any "encapsulated" and mysterious site you'll find.
 
So, if you want to keep my sympathy,
Solution 1° : you'd better write a clean time web service or a cleaner program
Solution 2° : Finally, a NTP application to synchronize the local computer time would perhaps be simpler, faster and much better..
 

 

QuestionWhy this when there is NTP?memberRamon Smits24 May '07 - 4:12 
I'm sorry to say but why use this solution when time-synchronisation is build-in in Windows? NTP even adjusts time according to the latency between the client and the server.
 
XP has configurable NTP settings in it's date time properties and all other Windows variations can do this on the commandline with the NET TIME command.
AnswerRe: Why this when there is NTP?memberGunasekaran Paramesh24 May '07 - 7:55 
Why Windows when there is Linux? I just thought to develop this when I found the sample service from Y!
 
Programming is fun indeed!!!
 
Param

GeneralRe: Why this when there is NTP?memberRamon Smits24 May '07 - 11:41 
I don't say programming isn't fun. I love programming but this just isn't the way to do time synchronisation. You should have made that clear in your article to user NTP for that and this is just a sort of webservice example.
 
Don't get me wrong.. go on with contributing articles but do point out your motivation to create the article in the first place and add pro's and con's if there are common other solutions available.
 
In other words.. innovate, don't immitate unless its better Smile | :)
AnswerRe: Why this when there is NTP?membersillett24 May '07 - 14:40 
In many cases, especially in a corporate environment, the NTP or TIME protocols are blocked. And one often finds in a Windows environment with a sloppy IT department that the Windows time server (typically the PDC Emulator in Active Directory) is off by several minutes.
 
Thus a method for time synchronization that uses HTTP and not NTP or TIME is quite useful when the ports are blocked as pretty much everyone allows outbound HTTP.
 
Thanks for the article.
 
Bob

GeneralRe: Why this when there is NTP?memberRamon Smits24 May '07 - 21:31 
Corporate environments have domains. Computers are within a domain and for security it is very critical that all computers within a domain are sharing the same time. If indeed the domain controllers are having a big offset then the administrators should sync their domain controllers with any of the *.pool.ntp.org servers. The solution is not to just adjust one pc in the network with this method.
GeneralRe: Why this when there is NTP?membersillett25 May '07 - 1:54 
Why are you so obstinate? Who appointed you the gatekeeper of what can be posted on CodeProject? He wrote this article because it was fun and the code does something useful in that it syncs time to Yahoo over HTTP. The fact that it uses HTTP and not NTP makes it useful.
 
The purpose of CodeProject is to share code snippets. This code can also be used as a template to interface with other Yahoo services. This code is a "for the sake of an example" project.
 
Crawl out from under your little bridge and learn some people skills.
AnswerRe: Why this when there is NTP?memberRamon Smits25 May '07 - 2:02 
If people just post everything they make up then the quality of CP.COM is degrading.
 
So lets wrap up all usefull protocols into webservices! Wow that would be a good idea! Lets just wrap up SMTP, NNTP, NTP, TELNET, FTP! That would them make them more accessible!
 
I respect skills but I really don't see them in this article. Instead of just insulting me and my opinion and free right to let me say why this really shouldn't be the way to go you are nagging without good arguments.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 24 May 2007
Article Copyright 2007 by Paramesh Gunasekaran
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid