Python循环定时服务功能(相似contrab)
Python实现的循环定时服务功能。类似于Linux下的contrab功能。主要通过定时器实现。
注:Python中的threading.timer是基于线程实现的。每次定时事件产生时。回调完响应函数后线程就结束。而Python中的线程是不能restart的,所以这样的循环定时功能必需要在每次定时响应完毕后再又一次启动还有一个定时事件。
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- #
- import subprocess
- from threading import Timer
- import time
- import os
- import sys
- if os.name == 'posix':
- def become_daemon(our_home_dir='.', out_log='/dev/null',
- err_log='/dev/null', umask=0o022):
- "Robustly turn into a UNIX daemon, running in our_home_dir."
- # First fork
- try:
- if os.fork() > 0:
- sys.exit(0) # kill off parent
- except OSError as e:
- sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
- sys.exit(1)
- os.setsid()
- os.chdir(our_home_dir)
- os.umask(umask)
- # Second fork
- try:
- if os.fork() > 0:
- os._exit(0)
- except OSError as e:
- sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
- os._exit(1)
- si = open('/dev/null', 'r')
- so = open(out_log, 'a+', 0)
- se = open(err_log, 'a+', 0)
- os.dup2(si.fileno(), sys.stdin.fileno())
- os.dup2(so.fileno(), sys.stdout.fileno())
- os.dup2(se.fileno(), sys.stderr.fileno())
- # Set custom file descriptors so that they get proper buffering.
- sys.stdout, sys.stderr = so, se
- else:
- def become_daemon(our_home_dir='.', out_log=None, err_log=None, umask=0o022):
- """
- If we're not running under a POSIX system, just simulate the daemon
- mode by doing redirections and directory changing.
- """
- os.chdir(our_home_dir)
- os.umask(umask)
- sys.stdin.close()
- sys.stdout.close()
- sys.stderr.close()
- if err_log:
- sys.stderr = open(err_log, 'a', 0)
- else:
- sys.stderr = NullDevice()
- if out_log:
- sys.stdout = open(out_log, 'a', 0)
- else:
- sys.stdout = NullDevice()
- class NullDevice:
- "A writeable object that writes to nowhere -- like /dev/null."
- def write(self, s):
- pass
- def outputLog(sLog):
- print sLog
- def toLog(sLog):
- sInfo = time.strftime("%y%m%d %H:%M:%S")
- sInfo += sLog
- outputLog(sInfo)
- def Log_Info(sLog):
- toLog('Info\t' + sLog)
- def Log_Error(sLog):
- toLog('error\t' + sLog)
- def Log_Debug(sLog):
- toLog('debug\t' + sLog)
- class TimerRunner:
- '''
- '''
- nTimeScds = 2 #时间间隔
- sCmd = 'calc'
- oTm = None
- @classmethod
- def becomeDaemonize(cls):
- become_daemon()
- @classmethod
- def RunCmd(cls):
- oSubPcs = subprocess.Popen(cls.sCmd, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
- while True:
- nReturnCode = oSubPcs.poll()
- if 0 == nReturnCode:
- Log_Info(oSubPcs.stdout.read())
- break
- elif 0 > nReturnCode:
- Log_Error(oSubPcs.stderr.read())
- break
- @classmethod
- def timerFun(cls):
- Log_Info("go to timer fun")
- cls.initTimer()
- cls.oTm.start() #再次启动计时,放在runcmd函数前,保证时间的准确性
- cls.RunCmd()
- Log_Info("exit timer fun")
- @classmethod
- def initTimer(cls):
- cls.oTm = Timer(cls.nTimeScds, cls.timerFun)
- @classmethod
- def run(cls):
- cls.initTimer()
- cls.timerFun()
- cls.becomeDaemonize()
- def main():
- TimerRunner.run()
Python循环定时服务功能(相似contrab)的更多相关文章
- Python实现FTP服务功能
本文从以下三个方面, 阐述Python如何搭建FTP服务器 一. Python搭建FTP服务器 二. FTP函数释义 三. 查看目录结构 四. 上传下载程序 一. Python搭建FTP服务器 1. ...
- 【Python】 用python实现定时数据解析服务(前言)
一.Why do it? 背景:项目里上传上来的数据都是未解析的数据,而且数据量还算挺庞大的,每天上传的数据有5kw左右,如果用数据库自带的作业来解析的话,数据库会造成严重的阻塞.因此打算把数据读到外 ...
- C# 创建Windows服务。服务功能:定时操作数据库 (转)
C# 创建Windows服务.服务功能:定时操作数据库 一.创建window服务 1.新建项目-->选择Windows服务.默认生成文件包括Program.cs,Service1.cs 2.在S ...
- python实现简单的循环购物车小功能
python实现简单的循环购物车小功能 # -*- coding: utf-8 -*- __author__ = 'hujianli' shopping = [ ("iphone6s&quo ...
- Python +crontab定时备份目录发送邮件
公司有一台静态页面展示服务器仅供给客户展示我们做的项目,当时买的时候是最低配,也就是磁盘空间为20G的系统盘,考虑到代码量很小所以没有另加磁盘,后来项目多了,就写了个crontab 定时备份目录. 就 ...
- [Java聊天室server]实战之五 读写循环(服务端)
前言 学习不论什么一个稍有难度的技术,要对其有充分理性的分析,之后果断做出决定---->也就是人们常说的"多谋善断":本系列尽管涉及的是socket相关的知识,但学习之前,更 ...
- python 循环语句 函数 模块
python循环语句 while循环语法结构 当需要语句不断的重复执行时,可以使用while循环 while expression: while_suite 语句ehile_suite会被连续不断的循 ...
- Solr定时导入功能实现
需要实现Solr定时导入功能的话,我们可以通过使用Solr自身所集成的dataimportscheduler调度器实现 下载对应的jar包,下载地址https://code.google.com/ar ...
- Python实现进度条功能
Python实现进度条功能 import sys, time def progress(percent, width=50): # 设置进度条的宽度 if percent >= 100: # 当 ...
随机推荐
- [分享] IMX6嵌入式开发板linux QT挂载U盘及TF卡
本文转自迅为开发板:http://www.topeetboard.com 开发平台:iMX6开发板 linux QT 系统下挂载 u 盘如下图所示,qt 启动之后,在超级终端中使用命令“mknod / ...
- 【git】搭建git服务器
在 Linux 下搭建 Git 服务器 目录 ① 安装 Git ② 服务器端创建 git 用户,用来管理 Git 服务,并为 git 用户设置密码 ③ 服务器端创建 Git 仓库 ④ 客户端 clon ...
- 《Java程序设计》课程试题
< Java程序设计 >课程试题 一.单项选择题(20题:每题2分,共40分) 1.若数组a定义为int[][]a=new int[3][4],则a是___. A)一维数组 B)二维数组 ...
- 富文本编辑器复制Wod字体问题
目前常用的富文本编辑器:百度版UEditor,wangEditor,ckeditor,kindeditor,TinyMCE.当Word复制文本粘贴到编辑器时,几乎都无法保证字体大小完全一致的问题. 想 ...
- selenium click radio
radio = dr.find_element_by_xpath('//*[@id="contentTable"]/tbody/tr[1]/td[1]/input') webdri ...
- linux 服务脚本
#!/bin/bash # # chkconfig: # description: my_SERVICE_NAME is a my Service # # common function . /etc ...
- MySQL异常:Caused by: com.mysql.jdbc.exceptions.MySQLTimeoutException: Statement cancelled due to timeout or client request
Caused by: com.mysql.jdbc.exceptions.MySQLTimeoutException: Statement cancelled due to timeout or cl ...
- tomcat idea 报权限错误
出现的错误提示如下: 下午9:11:27 All files are up-to-date下午9:11:27 All files are up-to-date下午9:11:27 Error runni ...
- Python之基础练习题
Python之基础练习题 1.执行 Python 脚本的两种方式 2.简述位.字节的关系 解:8位是一个字节 3.简述 ascii.unicode.utf-8.gbk 的关系 4.请写出 “李杰” 分 ...
- Python中的列表(2)
一.从列表中删除元素 使用del 语句删除. books = ['Pride and Prejudice','Jane Eyre','The Catcher in the Rye'] print(bo ...