-
-
Save ii0/97f469be477c35ab6d607be74cdc3a31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import win32serviceutil | |
import servicemanager | |
import win32event | |
import win32service | |
import time | |
import random | |
from pathlib import Path | |
class SMWinservice(win32serviceutil.ServiceFramework): | |
""" | |
Base class to create winservice in Python | |
""" | |
_svc_name_ = 'pythonService' | |
_svc_display_name_ = 'Python Service' | |
_svc_description_ = 'Python Service Description' | |
@classmethod | |
def parse_command_line(cls): | |
""" | |
ClassMethod to parse the command line | |
""" | |
win32serviceutil.HandleCommandLine(cls) | |
def __init__(self, args): | |
""" | |
Constructor of the winservice | |
""" | |
win32serviceutil.ServiceFramework.__init__(self, args) | |
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) | |
socket.setdefaulttimeout(60) | |
def SvcStop(self): | |
""" | |
Called when the service is asked to stop | |
""" | |
self.stop() | |
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) | |
win32event.SetEvent(self.hWaitStop) | |
def SvcDoRun(self): | |
""" | |
Called when the service is asked to start | |
""" | |
self.start() | |
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, | |
servicemanager.PYS_SERVICE_STARTED, | |
(self._svc_name_, '')) | |
self.main() | |
def start(self): | |
""" | |
Override to add logic before the start | |
eg. running condition | |
""" | |
pass | |
def stop(self): | |
""" | |
Override to add logic before the stop | |
eg. invalidating running condition | |
""" | |
pass | |
def main(self): | |
""" | |
Main class to be ovverridden to add logic | |
""" | |
pass | |
class PythonCornerExample(SMWinservice): | |
_svc_name_ = "PythonCornerExample" | |
_svc_display_name_ = "Python Corner's Winservice Example" | |
_svc_description_ = "That's a great winservice! :)" | |
def start(self): | |
self.isrunning = True | |
def stop(self): | |
self.isrunning = False | |
def main(self): | |
while self.isrunning: | |
random.seed() | |
x = random.randint(1, 1000000) | |
Path(f'c:\\{x}.txt').touch() | |
time.sleep(5) | |
if __name__ == '__main__': | |
PythonCornerExample.parse_command_line() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment