好的,所以我创建了一个获取当前时间的python服务,并针对目录中的所有文件进行检查。如果该目录中的文件与当前时间具有相同的时间,则应该读取该文件并按照里面的命令执行。例如:如果当前时间是7:30,那么如果它在' Time'中找到了一个文件。目录名为' 7_30.protocol' (可能' 07_30.protocol')它应该读取并执行里面的命令。如果这是当前时间,它工作正常,但如果它不是,你必须等待时间,那么它不会工作。这是我的代码。我做错了什么?我现在已经编辑添加调试文件了!
import win32service
import win32serviceutil
import win32event
from time import *
import glob, os, dw, winmod2
def trim_protocol(name):
return name[:-9]
class MySvc(win32serviceutil.ServiceFramework):
_svc_name_ = "MySvc"
_svc_display_name_ = "My Service"
_svc_description_ = "This is just My Service"
debug = open("C:/LIP/ServiceDebugging.txt", "w")
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.debug.write("Closing service...\n")
self.debug.write("Service closed!")
self.debug.close()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
import servicemanager
self.timeout = 3000
profile_filenames = []
for file in os.listdir("C:/LIP/LIP Source Files/Config/Commands/Profiles/Time"):
if file.endswith(".protocol"):
profile_filenames.append(file)
profile_titles = map(trim_protocol, profile_filenames)
profiles = list(profile_titles)
times = [i.replace('_', ':') for i in profiles]
HD = os.getenv("SystemDrive")
while 1:
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
if rc == win32event.WAIT_OBJECT_0:
break
else:
self.debug.write("Service running...\n")
current_time = strftime("%H:%M", localtime())
if current_time in times:
self.debug.write("Found a file matching the current time! Opening and running...\n")
filename = current_time.replace(":", "_")
filename = filename + ".protocol"
file = open(HD + "/LIP/LIP Source Files/Config/Commands/Profiles/Time/" + filename, "r")
commands = file.read()
exec(commands)
file.close()
current_time = strftime("%H:%M", localtime())
self.debug.write("Commands have been run! Sleeping till the next minute!...\n")
sleep(60)
else:
self.debug.write("No time match found! Moving on...\n")
print("Standing by...")
sleep(5)
continue
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MySvc)
告诉我您是否需要更多信息,或者这是否有意义!
编辑:开启赏金。我们来回答吧! 编辑:添加了调试文件。
答案 0 :(得分:1)
循环结束时的睡眠(5)
命令(就在continue语句之前),这样服务就不会在不安的循环中占用你的CPU:)