Python language to write computer time automatic synchronization gadget

Source: Internet
Author: User
Without saying much, gadgets require the following:
function requirement--automatically perform time synchronization after computer boot
Non-functional requirements-simple installation and installation without additional environment

First, the 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 use Python to write this tool. The specific code is as follows:

Get Network Time

The code is as follows:


Def getbeijintime ():
"""
Get GMT
"""
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

The code is as follows:


Def synclocaltime ():
"""
Synchronizing local time
"""
Logging.info ("Current local time is:%d-%d-%d%d:%d:%d"% time.localtime () [: 6])

Beijintime = Getbeijintime ()
If Beijintime is None:
Logging.info ("Get Beijintime is 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])

II. Deployment and Installation

In order for the Python program to run as a Windows service, you need to use Py2exe (to compile the Python program into EXE) and Python Win32 Extensions. (This component is relied upon by Py2exe to compile the Python code into a WINODWS service) to download and install the two components. After installation, locate the Py2exe Windows service sample in the Python installation directory ({pythonroot}\lib\site-packages\py2exe\samples\advanced\ myservice.py). Then follow this example to refine the above code.

Windows Services Sample

The 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 is not being run in the ' Frozen ' exe-file!!!
Win32serviceutil. Handlecommandline (Synctimeservice)



After that, write a steup.py file to generate the installation files.

setup.py

The code is as follows:


From Distutils.core Import Setup
Import Py2exe

Setup
# The first three parameters is not required, if at least a
# ' version ' is given, then a versioninfo resource was 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, such as:

Then run it in the console: setup.py Py2exe, everything goes well. The build and Dist directories are generated in the current directory.

Switch the console directory to the Dist directory, locate the Synctime.exe, and run it on the command line:

Synctime.exe–install (-remove) installs or removes the time synchronization service.

You can now run services.msc to see how the service is running

You can see that the service is not started and is started manually. Here you can right-click the Service Selection property to start the service manually and set the service to start automatically.

All right, I admit it. This kind of operation with the above requirements a bit out of the way, slightly trouble. In order to solve this problem, the natural thought is to use batch processing to do. Two batch files were built under the Dist directory:

Installservice.bat

The code is as follows:


@echo off

:: Install Windows Services
ECHO is installing the service, please wait ...
Synctime.exe-install

:: Set the service to start automatically
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

The code is as follows:


@echo off

:: Stop Service
Echo is stopping the service, please wait ...
sc stop Synctime

ECHO is uninstalling the service ...
:: Remove Windows Service
Synctime.exe-remove

After the Echo service uninstallation is complete, press any key to continue with the remaining uninstallation ...
Pause

OK, now it's time to send dist a bag for mom. However, it is too unprofessional to send a compressed package like this. The solution is to hit an install package, put the bat script into the installation package, and be called by the installation package when the program is installed. Here I am using nisi (it is very convenient to use the HM Vnisedit Packaging Wizard to generate a packaging script).

Third, final installation

Iv. End of

Legacy issues:

1. As you can see from the above, the installer displays the console window when it calls the batch process. This problem I find information on the Internet, NSIs has the relevant plug-in can hide the console window call bat file.
2, I have the source code to write log file operations, but the way Windows services run, log files can not be written, do not know there is no good solution.
3, 360 ... It's a real kill. Orz.

Time synchronization tool and source code: http://www.bitsCN.com/softs/74865.html

Compile method:

First step: Install the Python environment (what?) Don't have a python environment yet? ... - -!)
Step Two: Install dependent components
1, Py2exe (currently only supported to python2.7)
2. Python Win32 Extensions

Step three (optional): Install the NSIs environment, which is used to compile the script

Fourth step: Compiling synctime.py into a Windows program
1, in the current directory run "setup.py py2exe", the smooth words will be in the current directory generated dist and build directory

The fifth step: run, there are two modes of operation:
1. Copy the Installservice.bat and Removeservice.bat to the Dist to run
2 (relying on the third step), compiling the Synctime.nsi script with NSIs, generating the installation package, running 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.