1 def syncLocalTime():
2 """
3 同步本地时间
4 """
5 logging.info("current local time is: %d-%d-%d %d:%d:%d" % time.localtime()[:6])
6
7 beijinTime = getBeijinTime()
8 if beijinTime is None:
9 logging.info("get beijinTime is None, will try again in 30 seconds...")
10 timer = threading.Timer(30.0, syncLocalTime)
11 timer.start();
12 else:
13 logging.info("get beijinTime is: %d-%d-%d %d:%d:%d" % beijinTime[:6])
14
15 tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec = beijinTime[:6]
16 import os
17 os.system("date %d-%d-%d" % (tm_year, tm_mon, tm_mday)) #设置日期
18 os.system("time %d:%d:%d.0" % (tm_hour, tm_min, tm_sec)) #设置时间
19 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服务示例
1 import win32serviceutil
2 import win32service
3 import win32event
4 import win32evtlogutil
5
6 class SynctimeService(win32serviceutil.ServiceFramework):
7 _svc_name_ = "Synctime"
8 _svc_display_name_ = "Synctime"
9 _svc_description_ = "Synchronize local system time with beijin time"
10 _svc_deps_ = ["EventLog"]
11
12 def __init__(self, args):
13 win32serviceutil.ServiceFramework.__init__(self, args)
14 self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
15
16 def SvcStop(self):
17 self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
18 win32event.SetEvent(self.hWaitStop)
19
20 def SvcDoRun(self):
21 import servicemanager
22
23 # Write a 'started' event to the event log...
24 win32evtlogutil.ReportEvent(self._svc_name_,
25 servicemanager.PYS_SERVICE_STARTED,
26 0, # category
27 servicemanager.EVENTLOG_INFORMATION_TYPE,
28 (self._svc_name_, ''))
29
30 # wait for beeing stopped...
31 win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
32
33 # and write a 'stopped' event to the event log.
34 win32evtlogutil.ReportEvent(self._svc_name_,
35 servicemanager.PYS_SERVICE_STOPPED,
36 0, # category
37 servicemanager.EVENTLOG_INFORMATION_TYPE,
38 (self._svc_name_, ''))
39
40 if __name__ == '__main__':
41 # Note that this code will not be run in the 'frozen' exe-file!!!
42 win32serviceutil.HandleCommandLine(SynctimeService)
之后,再编写一个steup.py文件用来生成安装文件。
Setup.py
1 from distutils.core import setup
2 import py2exe
3
4 setup(
5 # The first three parameters are not required, if at least a
6 # 'version' is given, then a versioninfo resource is built from
7 # them and added to the executables.
8 version = "0.0.1",
9 description = "Synchroniz local system time with beijin time",
10 name = "sysctime",
11
12 # targets to build
13 # console = ["synctime.py"],
14 service=["synctime"]
15 )
编译生成windows程序,如下图: