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 ...
随机推荐
- 设计模式--中介(Mediator)模式
时隔很长一段时,现在又重温设计模式,上个星期学习<设计模式--代理(Proxy)模式>http://www.cnblogs.com/insus/p/4128814.html. 温故而知新, ...
- ASP.NET MVC5 网站开发实践
http://www.cnblogs.com/mzwhj/p/3538108.html
- 快捷获取浏览器(navigator对象)的全部属性
理论: navigator对象包含关于web浏览器的信息,浏览器的类型,版本信息都可以从该对象获取. 属性 说明 appCodeName 浏览器代码说明 appName 浏览器名称 appVe ...
- Java集合Iterator迭代器的实现
一.迭代器概述 1.什么是迭代器? 在Java中,有很多的数据容器,对于这些的操作有很多的共性.Java采用了迭代器来为各种容器提供了公共的操作接口.这样使得对容器的遍历操作与其具体的底层实现相隔离, ...
- ref与out的区别
若要使用 ref 参数,方法定义和调用方法均必须显式使用 ref 关键字,如下面的示例所示. class RefExample { static void Method(ref int i) { // ...
- 使用win2d实现萤火虫粒子效果
这几天我在做游戏的标题画面,需要实现随机飞舞的萤火虫.萤火虫会闪烁黄绿色的光,远近不同,并且飞出屏幕边界不久会自动飞回来. 我前一阵子用win2d写了个简单的游戏引擎(现在还是alpha阶段),用它可 ...
- bootstrap学习笔记(6)
滚动监听 滚动监听有两种方式: (1)通过属性控制 向想要滚动监听的元素添加如下属性data-spy="scroll",然后添加data- ...
- 【C#进阶系列】06 类型和成员基础
这些东西是基础中的基础,基本上是本书都会讲这个.但是很多东西到处都有,所以只捡了以下的这些写下来. 关于类型的可见性和可访问性 也就是public,internal这种东西,但是还是有个东西要提一下, ...
- Linux基础学习系列(一)
Linux是一种类似于UNIX的操作系统,由Linus Torvalds于1991年在minix操作系统的基础创建.Linux凭借其优良特性已经成为目前发展潜力最大的操作系统. Linux的版本有内核 ...
- [TypeScript] JSON对象转TypeScript对象范例
[TypeScript] JSON对象转TypeScript对象范例 Playground http://tinyurl.com/nv4x9ak Samples class DataTable { p ...