Skip to content

Commit 0856152

Browse files
authored
Upload python service file
1 parent b0ff52c commit 0856152

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

pyservice.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
# Dev By : Ali B Othman
5+
6+
import logging
7+
from logging.handlers import SysLogHandler
8+
import time,os
9+
10+
from service import find_syslog, Service
11+
12+
13+
class MyService(Service):
14+
def __init__(self, *args, **kwargs):
15+
super(MyService, self).__init__(*args, **kwargs)
16+
# Set logger (sys log)
17+
self.logger.addHandler(SysLogHandler(address=find_syslog(),
18+
facility=SysLogHandler.LOG_DAEMON))
19+
self.logger.setLevel(logging.INFO)
20+
21+
def run(self):
22+
# What you want from service To Do
23+
while not self.got_sigterm():
24+
self.logger.info("I'm working...")
25+
time.sleep(5)
26+
27+
28+
if __name__ == '__main__':
29+
# Service name
30+
servicename = 'My service'
31+
# Pid file name
32+
pidname = ('%s.pid' % servicename)
33+
import sys
34+
35+
if len(sys.argv) != 2:
36+
sys.exit('Syntax: %s COMMAND\n[--start] to start service.\n[--stop] to stop service.\n[--status] to check service status.' % sys.argv[0])
37+
38+
cmd = sys.argv[1].lower()
39+
# Pid dir
40+
service = MyService(servicename, pid_dir='/tmp')
41+
42+
if cmd == '--start':
43+
if service.is_running():
44+
print('Service is already running.\nUse (%s --stop) to stop service' % sys.argv[0])
45+
else:
46+
service.start()
47+
elif cmd == '--stop':
48+
if not service.is_running():
49+
print('Service is already not running.')
50+
else:
51+
try:
52+
while service.is_running():
53+
service.stop()
54+
# Don't change time.sleep(1)
55+
time.sleep(1)
56+
except Exception as e:
57+
if e == '[Errno 3] No such process':
58+
os.remove('/tmp/%s' % pidname)
59+
if pidname in os.listdir('/tmp'):
60+
os.remove('/tmp/%s' % pidname)
61+
elif cmd == '--status':
62+
if service.is_running():
63+
print("Service is running.")
64+
else:
65+
print("Service is not running.")
66+
else:
67+
sys.exit('Unknown command "%s".\n[--start] to start service.\n[--stop] to stop service.\n[--status] to check service status.' % cmd)

0 commit comments

Comments
 (0)