Python语言编写电脑时间自动同步小工具
话不多说,小工具需求如下:
功能需求 -- 电脑开机后自动执行时间同步
非功能需求 -- 安装执行简单,无需安装额外环境
一、代码实现
基于以上需求,思路如下:访问网络获取北京时间,然后调用命令行来设置系统时间。程序写成Windows Service,并设置为开机自动运行。正好前段时间在学习Python,所以打算用Python来写这个工具。具体代码如下:
获取网络时间
代码如下:
def getBeijinTime():
"""
获取北京时间
"""
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
同步本地系统时间
代码如下:
def syncLocalTime():
"""
同步本地时间
"""
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, will try again in 30 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])
二、部署安装
为了让Python程序能以Windows服务的方式运行,需要用到py2exe(用来把Python程序编译成exe)和Python Win32 Extensions 。(py2exe把Python代码编译成Winodws服务时依赖此组件)下载并安装这两个组件。安装完毕后,在Python的安装目录下找到py2exe的Windows Service示例({PythonRoot}\Lib\site-packages\py2exe\samples\advanced\MyService.py)。然后仿照这个示例将上面的代码完善一下。
Windows服务示例
代码如下:
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)
之后,再编写一个steup.py文件用来生成安装文件。
Setup.py
代码如下:
from distutils.core import setup
import py2exe
setup(
# The first three parameters are not required, if at least a
# '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"]
)
编译生成windows程序,如下图:
然后在控制台中运行:setup.py py2exe ,一切顺利的话会在当前目录下生成build和dist目录。
控制台目录切换到dist目录,找到synctime.exe,在命令行中运行:
synctime.exe –install (-remove) 安装或移除时间同步服务。
现在可以运行services.msc查看服务运行情况
可以看到服务并没有启动,而且启动方式为手动。在这里可以右击服务选择属性手动把服务启动起来,并且设置为服务自动启动。
好吧,我承认。这样操作跟上面的需求有点出入了,略显麻烦。为了解决这个问题,自然想到的是用批处理来做。在dist目录下分别建两个批处理文件:
installservice.bat
代码如下:
@echo off
:: 安装windows服务
echo 正在安装服务,请稍候...
synctime.exe -install
:: 设置服务自动启动
echo 正在启动服务...
sc config Synctime start= AUTO
:: 启动服务
sc start Synctime
echo 服务启动成功, 按任意键继续...
pause
removeserivce.bat
代码如下:
@echo off
:: 停止服务
echo 正在停止服务,请稍候...
sc stop Synctime
echo 正在卸载服务...
:: 删除windows服务
synctime.exe -remove
echo 服务卸载完成,请按任意键继续剩余卸载...
pause
好了,现在可以把dist打个包发给老妈用了。但是,这样发个一个压缩包,看起来也太不专业了。解决的办法是打一个安装包,把bat脚本打到安装包里,在安装程序时由安装包调用。这里我用的是NISI(使用HM VNISEdit打包向导来生成打包脚本非常方便)。
三、最终安装效果图
四、结尾
遗留的问题:
1、从上面的截图可以看到,安装程序在调用批处理时会显示出控制台窗口。这个问题我在网上查找资料,NSIS有相关的插件可以隐藏控制台窗口调用bat文件。
2、我源代码中有写日志文件的操作,但是以Windows服务的方式运行后,日志文件不能写了,不知道有没有好的解决办法。
3、360 ...真是要人命啊....Orz..
时间同步工具及源代码:http://www.bitsCN.com/softs/74865.html
编译方法:
第一步: 安装Python环境(什么?还没有Python环境?... - -!)
第二步: 安装依赖组件
1、py2exe (目前只支持到python2.7)
2、Python Win32 Extensions
第三步(可选):安装Nsis环境,用来编译脚本
第四步:将synctime.py编译成windows程序
1、在当前目录下运行"setup.py py2exe",顺利的话会在当前目录下生成dist和build目录
第五步: 运行,有两种运行方式:
1、将installservice.bat 和 removeservice.bat 拷贝到dist中运行即可
2(依赖第三步)、使用Nsis编译Synctime.nsi脚本,生成安装包, 安装后运行(推荐)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
