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 ...
随机推荐
- 分享一些WinForm数据库连接界面UI
1.动软代码生成器源码中. 2.DevExpress控件包中有类似的界面 3.代码生成器:http://www.csharpwin.com/csharpspace/11666r2577.shtml 4 ...
- ComponentOne Studio for Enterprise 2015 v1 全新发布
ComponentOne Studio 即将发布2015年的第一个版本.2015 v1版本聚焦于优化性能.提升数据可视化能力.加强数据管理以及更人性的输入方式及报表解决方案. 免费下载试用 WinFo ...
- markdown这么好用的东西我才知道。。。多么不折腾的我。。。
markdown 锚点 努力吧 我的网站 之前有个域名phifan.com没续费被抢了,之后又买了phifan.cn没续费被抢了,还剩下个plusnet.cn说什么也不能再丢掉了! package c ...
- [moka同学摘录]Yii2.0开发初学者必看
想要了解更多YII,PHP方面内容,请关注本博客. 基础总结 1.修改默认控制器/方法 yii默认是site控制器,可以在web.php中设置$config中的'defaultRoute'='xxxx ...
- Android系统兼容性问题(持续更新)
相信开发过一段Android的都被Android中的兼容性问题给折腾过,有时这确实很无奈,Android被不同的厂商改的七零八落的.本文主要总结下本人在实际的项目开发过程中所遇到的兼容性问题,以及最后 ...
- 写给java程序员的c++与java实现的一些重要细微差别
0.其实常规的逻辑判断结构.工具类.文件读写.控制台读写这些的关系都不大,熟悉之后,这些都是灵活运用的问题. 学习c/c++需要预先知道的一个前提就是,虽然有ANSI C标准,但是每个c/c++编译器 ...
- [TypeScript] TypeScript对象转JSON字符串范例
[TypeScript] TypeScript对象转JSON字符串范例 Playground http://tinyurl.com/njbrnrv Samples class DataTable { ...
- wap网站safari浏览器和微信cooke不能登录问题
wap网站safari浏览器cooke不能登录问题: http://wenku.baidu.com/link?url=VnPxl43PySYVygt09vkQ7xwxOD0JCXNtw3Fx7100j ...
- 使用svcutil.exe 工具来生成调用文件
svcutil.exe http://localhost:9065/ServiceDemo.svc?wsdl 这将生成一个配置文件和一个包含客户端类的代码文件. 下面我们就用这个是怎么生成的: 1,打 ...
- 【读书笔记】iOS-Xcode-查找特殊字符的方法
如图所示,为搜索图框,然后,点击放大镜图标------->Insert Pattern---->即可看到特殊字符----->选择特殊字符进行插入. 参考资料:<iOS开发进阶& ...