天天看点

Python实现系统时间自动校正

最近由于台式机CMOS电池没电了,每次开机后系统时间都会被初始化。出于每次都要重新设置系统时间太麻烦的考虑,今天用Python实现了系统开机自动校正时间的程序。大致的思路是:首先产生一个windows service,该service在被启动之后通过urllib获得标准北京时间,并根据标准时间校对系统时间。具体代码如下:

#SyncLocaltime.py
#-*-coding=gbk-*-
import urllib
import re
import os 
import time
import win32serviceutil
import win32service
import win32event
import win32evtlogutil

url = "http://www.beijing-time.org/time.asp"

def get_information(url):
    try:
        wp = urllib.urlopen( url ) 
    except :
        return [] 
    ch = wp.read()
    ch1 = re.sub( r'\s' , "" , ch )
    ch2 = ch1.split(";") 
    return ch2

def get_time():
    ans = [] 
    while True :
        ch = get_information( url );
        if len(ch) == 0 :
            print "30秒后将重新连接"
            time.sleep( 30 ) 
        else :
            break; 
    for i in range(1 , len( ch )-1 ):
        ss = re.search( r'\d' , ch[i] ).start()
        needed = ch[i][ss : len( ch[i] ) ]
        ans.append( int(needed) )
    os.system("date %d-%d-%d" % ( ans[0] , ans[1] , ans[2]) )
    os.system("time %d:%d:%d.0" % ( ans[4] , ans[5] ,ans[6]) )

class SyncLocaltime(win32serviceutil.ServiceFramework): #类名要与文件名一致
    _svc_name_ = "SyncLocaltime"    #服务名称
    _svc_display_name_ = "SyncLocaltime"
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        print '服务开始'
    
    def SvcDoRun(self):
        import servicemanager
        #------------------------------------------------------
        # Make entry in the event log that this service started
        #------------------------------------------------------
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
        #-------------------------------------------------------------
        # Set an amount of time to wait (in milliseconds) between runs
        #-------------------------------------------------------------
        self.timeout=100
        while 1:
            #-------------------------------------------------------
            # Wait for service stop signal, if timeout, loop again
            #-------------------------------------------------------
            rc=win32event.WaitForSingleObject(self.hWaitStop,self.timeout)
            #
            # Check to see if self.hWaitStop happened
            #
            if rc == win32event.WAIT_OBJECT_0:
                #
                # Stop signal encountered
                #
                break
            else:
                #
                # Put your code here
                #
                get_time() 
                break 
                print '服务运行中'
                time.sleep(1)
        #
        # Only return from SvcDoRun when you wish to stop
        #
        return
        
    def SvcStop(self):
#---------------------------------------------------------------------
        # Before we do anything, tell SCM we are starting the stop process.
#---------------------------------------------------------------------
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
#---------------------------------------------------------------------
        # And set my event
#---------------------------------------------------------------------
        win32event.SetEvent(self.hWaitStop)
        print '服务结束'
        return
    
if __name__=='__main__':
        win32serviceutil.HandleCommandLine( SyncLocaltime )
           

为了让用户在没有python的环境下也可以运行该程序,这里用py2exe模块将py程序转换为exe文件。转换过程只需要在SyncLocaltime.py文件的目录下创建一个setup.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 = "SyncLocaltime",

	# targets to build
	service=["SyncLocaltime"]
)
           

这两个文件都建立好之后,就可以生成exe文件,并将服务添加都windows服务项中并启动服务了。具体批处理文件为:

python setup.py py2exe       //将SyncLocaltime.py转换为exe文件,生成build和dist文件夹,SyncLocaltime.exe文件位于dist中
pause
cd dist				
SyncLocaltime.exe -install	//安装服务,将服务添加到windows服务项中
pause
           

执行完上述批处理文件之后,我们就可以在运行->services.msc中打开系统服务,在其中查找一个叫做“SyncLocaltime”的服务,该服务现在默认是手动,并且未启动的,可以通过右键->启动,来启动该服务,服务启动之后就会将系统时间设置为北京标准时间。

这样在服务安装好之后,我们还需要在服务中手动启动服务,显然还不够便捷。这里我们可以在dist添加两个批处理文件startService.bat和stopService.bat来达到上述的效果。具体代码为:

#startService.bat
@echo off 
echo 正在安装服务,请稍候...
SyncLocaltime.exe -install

echo 正在启动服务...
sc config SyncLocaltime start= auto
sc start SyncLocaltime

echo 服务启动成功
pause

#stopService.bat
@echo off
echo 正在停止服务,请稍候...
sc stop SyncLocaltime

echo 正在卸载服务...
SyncLocaltime.exe -remove

echo 服务卸载成功
pause
           

到这里我们就可以将dist文件打包使用了,在使用的时候startService.bat用于启动服务,stopService.bat用于关闭服务。

但是作为一个软件,这样会显得比较寒颤,我们最好能将dist文件打包成一个setup.exe。用户只需要下载setup.exe安装包,然后安装成功就可以实现系统时间自动校正的功能。这里我使用NINS工具对dist进行打包。

首先需要下载:NINS 和 NIS Edit这两个软件,然后对软件进行安装。具体的过程可以参考:NINS打包图文教程。最后生成一个setup.exe就是用户要下载的安装包。

至此,windows系统时间的自动校正已圆满解决。