Words are not much said, the requirements of small tools are as follows:
Functional requirements--automatic execution time synchronization after computer boot
Non-functional requirements-simple installation, no need to install additional environment
One, code implementation
Based on the above requirements, the idea is as follows: Access the network to get Beijing time, and then call the command line to set the system time. The program is written as a Windows Service and is set to run automatically. I was learning python just a while ago, so I'm going to write this tool in Python. The specific code is as follows:
Get Network Time
Copy Code code as follows:
Def getbeijintime ():
"""
Get the
"""
Try
conn = Httplib. Httpconnection ("www.beijing-time.org")
Conn.request ("Get", "/time.asp")
Response = Conn.getresponse ()
Print Response.Status, Response.reason
If Response.Status = 200:
#解析响应的消息
result = Response.read ()
Logging.debug (Result)
data = Result.split ("\ r \ n")
Year = Data[1][len ("Nyear") +1:len (Data[1])-1]
month = Data[2][len ("Nmonth") +1:len (Data[2])-1]
Day = Data[3][len ("Nday") +1:len (Data[3])-1]
#wday = Data[4][len ("Nwday") +1:len (Data[4])-1]
hrs = Data[5][len ("nhrs") +1:len (Data[5])-1]
minute = Data[6][len ("Nmin") +1:len (Data[6])-1]
SEC = Data[7][len ("nsec") +1:len (Data[7])-1]
Beijintimestr = "%s/%s/%s%s:%s:%s"% (year, month, day, hrs, minute, sec)
Beijintime = Time.strptime (Beijintimestr, "%y/%m/%d%x")
Return Beijintime
Except
Logging.exception ("Getbeijintime except")
Return None
Synchronizing Local System time
Copy Code code as follows:
Def synclocaltime ():
"""
Synchronize local time
"""
Logging.info ("Current Local:%d-%d-%d%d:%d:%d"% time.localtime () [: 6])
Beijintime = Getbeijintime ()
If Beijintime is None:
Logging.info ("Get Beijintime are None, would try again in seconds ...")
Timer = Threading. Timer (30.0, Synclocaltime)
Timer.start ();
Else
Logging.info ("Get Beijintime is:%d-%d-%d%d:%d:%d"% beijintime[:6])
Tm_year, Tm_mon, Tm_mday, Tm_hour, tm_min, tm_sec = Beijintime[:6]
Import OS
Os.system ("Date%d-%d-%d"% (Tm_year, Tm_mon, tm_mday)) #设置日期
Os.system ("Time%d:%d:%d.0"% (Tm_hour, tm_min, tm_sec)) #设置时间
Logging.info ("Synclocaltime complete, current local time:%d-%d-%d%d:%d:%d \ n"% time.localtime () [: 6])
Second, deployment installation
In order for a Python program to run as a Windows service, Py2exe (used to compile the Python program into an EXE) and Python Win32 Extensions are needed. (Py2exe the Python code as a WINODWS service relies on this component) to download and install the two components. After installation, locate the Py2exe Windows Service sample under the Python installation directory ({pythonroot}\lib\site-packages\py2exe\samples\advanced\ myservice.py). Then follow this example to refine the code above.
Windows Services Sample
Copy Code code as follows:
Import Win32serviceutil
Import Win32service
Import Win32event
Import Win32evtlogutil
Class Synctimeservice (Win32serviceutil. Serviceframework):
_svc_name_ = "Synctime"
_svc_display_name_ = "Synctime"
_svc_description_ = "Synchronize Local system time with Beijin time"
_svc_deps_ = ["EventLog"]
def __init__ (self, args):
Win32serviceutil. Serviceframework.__init__ (self, args)
Self.hwaitstop = win32event. CreateEvent (None, 0, 0, none)
def svcstop (self):
Self. Reportservicestatus (Win32service. service_stop_pending)
Win32event. SetEvent (Self.hwaitstop)
def svcdorun (self):
Import ServiceManager
# Write A ' started ' event to the event log ...
Win32evtlogutil. ReportEvent (Self._svc_name_,
ServiceManager. Pys_service_started,
0, # Category
ServiceManager. Eventlog_information_type,
(Self._svc_name_, ")"
# wait for beeing stopped ...
Win32event. WaitForSingleObject (Self.hwaitstop, win32event. INFINITE)
# and write a ' stopped ' to the event log.
Win32evtlogutil. ReportEvent (Self._svc_name_,
ServiceManager. Pys_service_stopped,
0, # Category
ServiceManager. Eventlog_information_type,
(Self._svc_name_, ")"
if __name__ = = ' __main__ ':
# Note, this code won't be run ' Frozen ' exe-file!!!
Win32serviceutil. Handlecommandline (Synctimeservice)
Then write a steup.py file to build the installation file.
setup.py
Copy Code code as follows:
From Distutils.core Import Setup
Import Py2exe
Setup
# The three parameters are not required, if at least a
# ' version ' is given, then a versioninfo resource are built from
# them and added to the executables.
Version = "0.0.1",
Description = "Synchroniz Local system time with Beijin time",
Name = "Sysctime",
# Targets to build
# console = [' synctime.py '],
service=["Synctime"]
)
Compile the build Windows program, as shown in the following figure:
Then run in the console: setup.py Py2exe, everything goes well. Build and Dist directories are generated in the current directory.
Console directory switch to dist directory, find Synctime.exe, run on the command line:
Synctime.exe–install (-remove) installs or removes time Synchronization services.
You can now run services.msc to see the service running
You can see that the service is not started, and the startup mode is manual. Here you can right-click the service Selection property to manually start the service and set the service to start automatically.
Well, I admit it. This operation with the above demand a little different, slightly trouble. To solve this problem, the natural idea is to use batch processing to do. Two batch files were built under the Dist directory:
Installservice.bat
Copy Code code as follows:
@echo off
:: Installing Windows Services
ECHO is installing the service, please wait ...
Synctime.exe-install
:: Set the service to start automatically
ECHO is starting service ...
sc config synctime start= AUTO
:: Start Service
SC start Synctime
Echo Service started successfully, press any key to continue ...
Pause
Removeserivce.bat
Copy Code code as follows:
@echo off
:: Stop Service
Echo is stopping the service, please wait ...
sc stop Synctime
echo is uninstalling service ...
:: Removing Windows Services
Synctime.exe-remove
Echo Service Uninstall complete, press any key to continue remaining uninstall ...
Pause
OK, now you can send dist a bag for mom to use. However, it seems too unprofessional to send a compressed package like this. The solution is to play an installation package, hit the bat script into the installation package, and then invoke the installation package when installing the program. Here I use Nisi (The HM Vnisedit Pack Wizard is handy for generating packaged scripts).
Third, the final installation effect chart
Four, the end
Legacy issues:
1, from the above screenshot can be seen, the installer in the call batch processing will display the console window. This problem I look up on the Internet, NSIs has related plug-ins can hide the console window call bat file.
2, I have the source code to write the operation of the log file, but the way Windows services run, log files can not write, do not know if there is no good solution.
3, 360 ... It's a real life. Orz..
Time synchronization tool and source code: http://www.jb51.net/softs/74865.html
Compilation method:
First step: Install the Python environment (what?) No Python environment yet? ... - -!)
Step Two: Install the dependency component
1, Py2exe (currently only support to python2.7)
2, Python Win32 Extensions
Third step (optional): Install the NSIs environment to compile the script
Step Fourth: Compile synctime.py into a Windows program
1, in the current directory run "setup.py py2exe", smooth words will be generated in the current directory dist and build directory
Step Fifth: Run, there are two ways to run:
1, the Installservice.bat and removeservice.bat copy to the Dist run can
2 (rely on the third step), compile Synctime.nsi script using NSIs, build installation package, run after installation (recommended)