A daemon process class in python
In everbright task schedule project, we need some daemon process to do certain work, here is a example of daemon class:
#encoding=utf-8
#!/usr/bin/env python import sys, os, time, atexit
from signal import SIGTERM
Basedir='/home/ronglian/project/taskschedule'
class Daemon:
"""
A generic daemon class. Usage: subclass the Daemon class and override the run() method
"""
def __init__(self, pidfile, stderr=Basedir+'/logs/deamon_err.log', stdout=Basedir+'/logs/deamon_out.log', stdin='/dev/null'):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pidfile = pidfile def daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1) # decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0) # do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1) # redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, 'r')
so = file(self.stdout, 'a+')
se = file(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile,'w+').write("%s\n" % pid) def delpid(self):
os.remove(self.pidfile) def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None if pid:
message = "pidfile %s already exist. Daemon already running?\n"
sys.stderr.write(message % self.pidfile)
sys.exit(1) # Start the daemon
self.daemonize()
self.run() def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart # Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1) def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start() def run(self):
"""
You should override this method when you subclass Daemon. It will be called after the process has been
daemonized by start() or restart().
"""
Here is a example how to use the class, need to rewrite the run function in parent calss:
#encoding=utf-8 import sys, time
from daemon import Daemon
import dbaction
import Task
import getdependency
from tslogging import GlobalLogging as Logging class sys_sync_task_mgr(Daemon):
def __init__(self,temppath,starttime,frequency):
Daemon.__init__(self,temppath)
self.starttime = starttime
self.frequency = frequency def run(self): while True:
tasknolist= self.get_task_list() if len(tasknolist['sys_task']) > 0:
if time.ctime()>self.starttime:
Logging.getLog().info('Available system task list:%s'%(str(tasknolist['sys_task'])))
try:
for taskno in tasknolist['sys_task']:
Logging.getLog().info('Start running system task:%s'%str(taskno))
task = Task.sys_sync_task(taskno)
task.task_run()
except Exception, ex:
print 'hello'
Logging.getLog().error( "Exception in class: 'sys_sync_task_mgr' function:'run' :"+str(ex))
else:
print 'hello'
Logging.getLog().warn('Time to run the tasks still not reach.')
time.sleep(self.frequency)
def get_task_list(self):
tasklist = getdependency.task_dependency([],3,1).get_executable_task()
return tasklist #main function
if __name__ == "__main__":
daemon = sys_sync_task_mgr('/tmp/daemon_sys_sync_task_mgr.pid',time.ctime(),20)
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
A daemon process class in python的更多相关文章
- Run python as a daemon process
I am using `&`: why isn't the process running in the background? No problem. We won't show y ...
- Android Studio: Failed to sync Gradle project 'xxx' Error:Unable to start the daemon process: could not reserve enough space for object heap.
创建项目的时候报错: Failed to sync Gradle project 'xxx' Error:Unable to start the daemon process: could not r ...
- Android Studio新建了一个项目提示Error:Unable to start the daemon process
提示如下错误:
- 越狱开发-创建真正的后台程序(Daemon Process)
在网上搜索了一下如何在IOS上面实现Daemon Process,只有chrisalvares的博客中有过详细的描述,但是其博客中描述的较为复杂, 参考stackoverflow中的一个问答: htt ...
- 【error】Gradle sync failed: Unable to start the daemon process.【已解决】
---恢复内容开始--- 在克隆GIT项目后,Android Studio 报错: Gradle sync failed: Unable to start the daemon process. Th ...
- Android studio Unable to start the daemon process
Unable to start the daemon process.This problem might be caused by incorrect configuration of the da ...
- ionic android - Unable to start the daemon process. Could not reserve enough space for 2097152KB object heap
Unzipping C:\Users\app\.gradle\wrapper\dists\gradle-4.1-all\bzyivzo6n839fup2jbap0tjew\gradle-4.1-all ...
- android studio Error:Unable to start the daemon process【转】
本文转载自:https://blog.csdn.net/dhx20022889/article/details/44919905 我在用android studio 做一个小项目,在家里的mac电脑中 ...
- Daemon Process
Daemon Process 守护进程(Daemon)是运行在后台的一种特殊进程.它独立于控制终端并且周期性地执行某种任务或等待 处理某些发生的事件.守护进程是一种很有用的进程. Lin ...
随机推荐
- 微信公众平台入门开发教程.Net(C#)框架
一.序言 一直在想第一次写博客,应该写点什么好?正好最近在研究微信公众平台开发,索性就记录下,分享下自己的心得,也分享下本人简单模仿asp.net运行机制所写的通用的微信公众平台开发.Net(c#)框 ...
- 1. windows环境安装Node.js
1. 下载 地址: https://nodejs.org/en/ 2. 下载最新版本v6.1.0 Currrent
- PHP simplexml_load_string 过滤<![CDATA[XXXX]]>
首先说说过滤<![CDATA[XXXX]]>干嘛用的. 这东西主要是防止XML里面嵌套HTML标签导致XML样式错乱的. 过滤很简单: $response = str_replace( a ...
- 关于SQL Server的WITH(NOLOCK)和(NOLOCK)
The difference is that you should be using the syntax WITH (NOLOCK) (or WITH (<any table hint> ...
- .net经验积累
希望对.net编程者有所帮助 1.学会配置环境变量 1.我的电脑-属性-环境变量-双击下面的path-粘贴路径 2.ctrl+r 输入软件名字按回车 2.常用vs2010快捷键 代码格式化:ct ...
- java微信开发框架wechat4j入门教程
wechat4j What is wechat4j? wechat develop framework for java(微信开发框架JAVA版,最简单易用微信开发框架) wechat4j可以用来干什 ...
- Cache&Session Viewer
用于查看和删除网站Cache https://github.com/sdf333/Aspy
- PHP调用SQL Server存储过程
一.安装SQL Server Driver for PHP 在微软官网上发现了这个东西,他提供了一套PHP对MS2005/2008操作的全新函数库,并且支持UTF8,作为PHP的扩展运行.看来 ...
- Vue表单
gitHub地址: https://github.com/lily1010/vue_learn/tree/master/lesson11 一 vue表单 实在是太简单了,直接来个例子 <!DOC ...
- while循环语句的使用
说明:先判断表达式,后执行语句,while循环称为当型循环. 如果指定的条件为真(表达式为非0)时,执行while语句中的内嵌语句. 格式:while (表达式) //判断括号内表达式 真(tru ...