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 ...
随机推荐
- MIME(Multipurpose Internet Mail Extensions)的简介
多用途互联网邮件扩展类型(MIME) 作用:用于标识Web资源类型(Multipurpose Internet Mail Extensions,MIME) 效果:Web上MIME为每种类型的资源提供一 ...
- csharp: Domain-Driven Design(领域驱动设计)
http://dddsample.sourceforge.net/ https://github.com/citerus/dddsample-core http://dddsamplenet.code ...
- 从零开始学习Linux (cd命令)
上一篇博客中提到,我们学习命令大多都要参考 --help 这个选项.但是cd命令并没有这个选项. 我们可以通过 help cd 来查看cd的使用方式.其实cd命令挺简单的,它的作用是进入文件夹,也就是 ...
- PHP学习笔记:通过curl实现采集网站内容
关于curl,请各位同学自行百度,我直接上案例. 首先开启你的curl拓展,在php.ini文件把curl拓展开启,即取消extension=php_curl.dll的分号. eg:利用curl采集网 ...
- Maven的安装使用以及 Maven+Spring hello world example
关于Maven Maven是一个用于项目构建的工具,通过它便捷的管理项目的生命周期.即项目的jar包依赖,开发,测试,发布打包. 做过.NET的人应该会联想到Nuget,是的Maven其实就是java ...
- SharpGL学习笔记(十五) 纹理映射
纹理映射非常实用,在游戏场景中已经无所不在了. 一个较少的多边形构成的模形,配合好的纹理贴图进行映射,可以得到逼真的效果.游戏中的天空,地面,墙面,和植物都是纹理贴图进行映射的. 例如最终幻想8的男女 ...
- iOS 七牛云上传并获取图片----【客户端】
最近做了七牛云存储的有关内容,涉及到与后台交互获取验证的token,无奈,后台自命清高,不与理会,没办法呀,于是自己搞呗.首先呢在在七牛上注册一个账号,然后呢添加一个存储空间这时候空间名 ...
- [WCF REST] Web消息主体风格(Message Body Style)
对于Web HTTP编程模型来说,服务契约中作为操作的方法无须应用OperationContractAttribute特性,只需要根据需要应用WebGetAttribute与WebInvokeAttr ...
- ssh无法登录linux服务器的解决办法
最近之前使用的一台linux服务器被长官重装系统了,导致ssh登录的时候出现如下错误: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ...
- 类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。
错误的写法: if (this.GridView1.Rows.Count > 0) { string style = @"<style& ...