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)的更多相关文章

  1. Python实现FTP服务功能

    本文从以下三个方面, 阐述Python如何搭建FTP服务器 一. Python搭建FTP服务器 二. FTP函数释义 三. 查看目录结构 四. 上传下载程序 一. Python搭建FTP服务器 1. ...

  2. 【Python】 用python实现定时数据解析服务(前言)

    一.Why do it? 背景:项目里上传上来的数据都是未解析的数据,而且数据量还算挺庞大的,每天上传的数据有5kw左右,如果用数据库自带的作业来解析的话,数据库会造成严重的阻塞.因此打算把数据读到外 ...

  3. C# 创建Windows服务。服务功能:定时操作数据库 (转)

    C# 创建Windows服务.服务功能:定时操作数据库 一.创建window服务 1.新建项目-->选择Windows服务.默认生成文件包括Program.cs,Service1.cs 2.在S ...

  4. python实现简单的循环购物车小功能

    python实现简单的循环购物车小功能 # -*- coding: utf-8 -*- __author__ = 'hujianli' shopping = [ ("iphone6s&quo ...

  5. Python +crontab定时备份目录发送邮件

    公司有一台静态页面展示服务器仅供给客户展示我们做的项目,当时买的时候是最低配,也就是磁盘空间为20G的系统盘,考虑到代码量很小所以没有另加磁盘,后来项目多了,就写了个crontab 定时备份目录. 就 ...

  6. [Java聊天室server]实战之五 读写循环(服务端)

    前言 学习不论什么一个稍有难度的技术,要对其有充分理性的分析,之后果断做出决定---->也就是人们常说的"多谋善断":本系列尽管涉及的是socket相关的知识,但学习之前,更 ...

  7. python 循环语句 函数 模块

    python循环语句 while循环语法结构 当需要语句不断的重复执行时,可以使用while循环 while expression: while_suite 语句ehile_suite会被连续不断的循 ...

  8. Solr定时导入功能实现

    需要实现Solr定时导入功能的话,我们可以通过使用Solr自身所集成的dataimportscheduler调度器实现 下载对应的jar包,下载地址https://code.google.com/ar ...

  9. Python实现进度条功能

    Python实现进度条功能 import sys, time def progress(percent, width=50): # 设置进度条的宽度 if percent >= 100: # 当 ...

随机推荐

  1. swift 即使不使用oc的动态派发机制也应该借鉴isa类型识别机制

    目前的消息派发机制真的很鸡肋. 简直是一堆狗屎. 类型信息中包含所有需要动态派发的函数:这个包含两类:类和protocol: 在编译时,首先搜索动态派发列表: 动态派发列表没有,在搜索静态派发列表: ...

  2. /etc/auto.master - automounter的主映射文件

    描述(DESCRIPTION) 当机器启动自动挂载器时, autofs(8) 脚本就会查寻 auto.master 这个主映射文件.文件中的每行分别指明,一个挂载点以及与对应的需要被挂载的文件系统.通 ...

  3. WM

    #define WM_NULL 0x0000 #define WM_CREATE 0x0001 #define WM_DESTROY 0x0002 #define WM_MOVE 0x0003 #de ...

  4. ARP是如何工作的?

    我们知道,当我们在浏览器里面输入网址时,DNS服务器会自动把它解析为IP地址,浏览器实际上查找的是IP地址而不是网址.那么IP地址是如何转换为第二层物理地址(即MAC地址)的呢? 在局域网中,这是通过 ...

  5. gifsicle for linux ----------gif 图像处理

    1.gifsicle 在linux 中的使用下载gifsicle yum install gifsicle 若发现没有此包 ,更新epel第三方软件库 sudo yum install epel-re ...

  6. Oracle排名函数(Rank)实例详解

    这篇文章主要介绍了Oracle排名函数(Rank)实例详解,需要的朋友可以参考下     --已知:两种排名方式(分区和不分区):使用和不使用partition --两种计算方式(连续,不连续),对应 ...

  7. Linux下启动tomcat报java.lang.OutOfMemoryError: PermGen space

    一.错误信息 java.lang.reflect.InvocationTargetException    at sun.reflect.NativeMethodAccessorImpl.invoke ...

  8. 并不简单的Integer

    Integer是一个看着挺简单的,其实还是有点不一样,Integer是一个int的包装类,它是可以起到缓存作用的,在java基础里说过它的范围是(-128-127)在这个返回是有缓存的,不会创建新的I ...

  9. [Python3网络爬虫开发实战] 3.1.3-解析链接

    前面说过,urllib库里还提供了parse这个模块,它定义了处理URL的标准接口,例如实现URL各部分的抽取.合并以及链接转换.它支持如下协议的URL处理:file.ftp.gopher.hdl.h ...

  10. vim使用学习

    1.1在正常模式下,使用h,j,k,l实现左,下,上,右移动. (如果不再正常模式下,使用Esc键进入正常模式) 1.2退出vim,先进入到正常模式,输入:q!退出,但不保存任何修改. 1.3在正常模 ...