The tool for automatic synchronization of computer time written in Python

Source: Internet
Author: User

To put it bluntly, the demand for gadgets is as follows:
Functional requirements-Automatic Time Synchronization After the computer is started
Non-functional requirements-simple installation and execution, no additional Environment installation required

I. 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 set to run automatically upon startup. I was learning Python some time ago, so I plan to use Python to write this tool. The Code is as follows:

Get Network Time

Copy codeThe Code is as follows: def getBeijinTime ():
"""
Get Beijing Time
"""
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:
# Parse the Response Message
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" % (year, month, day, hrs, minute, sec)
BeijinTime = time. strptime (beijinTimeStr, "% Y/% m/% d % X ")
Return beijinTime
Except t:
Logging. exception ("getBeijinTime failed t ")
Return None

Synchronize local system timeCopy codeThe Code is as follows: def syncLocalTime ():
"""
Synchronize local time
"""
Logging.info ("current local time is: % d-% d: % d" % time. localtime () [: 6])

BeijinTime = getBeijinTime ()
If beijinTime is None:
Logging.info ("get beijinTime is None, will try again in 30 seconds ...")
Timer = threading. Timer (30.0, syncLocalTime)
Timer. start ();
Else:
Logging.info ("get beijinTime is: % 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" % (tm_year, tm_mon, tm_mday) # Set the date
OS. system ("time % d: % d.0" % (tm_hour, tm_min, tm_sec) # set the time
Logging.info ("syncLocalTime complete, current local time: % d-% d: % d \ n" % time. localtime () [: 6])

Ii. Deployment and Installation

To enable the Python program to run as a Windows Service, py2exe (used to compile the Python program into exe) and Python Win32 Extensions are required. (Py2exe depends on this component when compiling Python code into the Winodws Service) download and install these two components. After installation, find the Windows Service example of py2exe In the Python installation directory ({PythonRoot} \ Lib \ site-packages \ py2exe \ samples \ advanced \ MyService. py ). Then, follow this example to complete the above Code.

Windows service example

Copy codeThe Code is 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' event 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 that this code will not be run in the 'frozen' exe-file !!!
Win32serviceutil. HandleCommandLine (SynctimeService)

Then, write a steup. py file to generate the installation file.

Setup. py

Copy codeThe Code is as follows: from distutils. core import setup
Import py2exe

Setup (
# The first three parameters are not required, if at least
# 'Version' is given, then a versioninfo resource is 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 and generate a windows program, for example:

Then run setup. py py2exe in the console. If everything goes well, the build and dist directories will be generated in the current directory.

Switch the control table directory to the distdirectory, find synctime.exe, and run the following command in the command line:

Synctime.exe-install (-remove) to install or remove the time synchronization service.

Now you can run services. msc to view the service running status.

You can see that the service is not started and the start mode is manual. Here, you can right-click the Service Selection attribute to manually start the service and set it to automatic start of the service.

Okay, I admit it. In this way, the operation is somewhat different from the above requirement, and it is a little troublesome. To solve this problem, we naturally think of batch processing. Create two batch files in the dist directory:

Installservice. bat

Copy codeThe Code is as follows: @ echo off

: Install windows Services
Echo is installing the service. Please wait...
Synctime.exe-install

: Set automatic Service Startup
Echo is starting the service...
SC config Synctime start = AUTO

: Start the service
SC start Synctime

Echo service started successfully. Press any key to continue...
Pause

Removeserivce. bat

Copy codeThe Code is as follows: @ echo off

: Stop the service
Echo is stopping the service. Please wait...
SC stop Synctime

Echo is uninstalling the service...
: Delete windows Services
Synctime.exe-remove

The echo service has been uninstalled. Press any key to continue uninstalling...
Pause

Now you can pack the dist and send it to your mom. However, sending a compressed package looks too unprofessional. The solution is to create an installation package, mount the bat script to the installation package, and call the installation package during installation. Here I use NISI (it is very convenient to use the HM VNISEdit packaging Wizard to generate the packaging script ).

Iii. Final Installation

Iv. End

Legacy problems:

1. As shown in the preceding figure, the installer will display a console window when calling batch processing. I am searching for information on the Internet. NSIS has related plug-ins to hide the bat file called in the console window.
2. I have operations on writing log files in the source code, but after running in Windows service mode, the log files cannot be written. I wonder if there is any good solution.
3. 360... it's really a matter of life... Orz ..

Time Synchronization tool and source code: http://www.jb51.net/softs/74865.html

Compilation Method:

Step 1: Install the Python environment (what? No Python environment yet ?... --!)
Step 2: Install dependency Components
1. py2exe (currently only python2.7 is supported)
2. Python Win32 Extensions

Step 3 (optional): Install the Nsis environment to compile the script

Step 4: Compile synctime. py into a windows program
1. Run "setup. py py2exe" in the current directory. If it succeeds, the dist and build directories will be generated in the current directory.

Step 5: run in two ways:
1. Copy installservice. bat and removeservice. bat to dist to run the command.
2. Use Nsis to compile the Synctime. nsi script, generate the installation package, and run it after installation (recommended)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.