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. 一起来学SpringBoot(十七)优雅的参数校验

    参数校验在开发中经常需要写一些字段校验的代码,比如字段非空,字段长度限制,邮箱格式验证等等,写这些与业务逻辑关系不大的代码个人感觉有两个麻烦: 验证代码繁琐,重复劳动方法内代码显得冗长每次要看哪些参数 ...

  2. C#在Excel的簡單操作--適用:與DB數據的簡單交互

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  3. 在vue中场景,循环行,点击当前行编辑数据

    当前列表 点击编辑,行变为编辑框. <Row style="color:#999;margin-bottom:11px"> <Row style="ma ...

  4. bash基础——管道符、通配符

    1.多命令顺序执行 多命令顺序执行 格式 作用 ; 命令1 ; 命令2 多个命令之间没有任何逻辑联系 && 命令1&&命令2 逻辑与 当命令1正确执行,则命令2才会执行 ...

  5. 基于oauth2.0实现应用的第三方登录

    OAuth2 OAuth2所涉及到的对象主要有以下四个: Client 第三方应用,我们的应用就是一个Client Resource Owner 资源所有者,即用户 Authorization Ser ...

  6. vim跳转(一)

    参考资料:http://easwy.com/blog/archives/advanced-vim-skills-basic-move-method/ 在normal模式下使用如下命令 1.h, j, ...

  7. 基于js插件的文件上传

    <?php /** * Created by PhpStorm. * User: GyCCo. * Date: 05/02/2018 * Time: 4:46 PM */ session_sta ...

  8. [Luogu] P1156 垃圾陷阱

    题目描述 卡门――农夫约翰极其珍视的一条Holsteins奶牛――已经落了到“垃圾井”中.“垃圾井”是农夫们扔垃圾的地方,它的深度为D(2≤D≤100)英尺. 卡门想把垃圾堆起来,等到堆得与井同样高时 ...

  9. 反连接NOT EXISTS子查询中有or 谓词连接条件SQL优化一例

    背景 今天在日常数据库检查中,发现一SQL运行时间特别长,于是抓取出来,进行优化. 优化前: 耗时:503s 返回:0 SQL代码 SELECT * FROM MM_PAYABLEMONEY_TD P ...

  10. 自己封装的js工具

    // 封装函数insertAfter;功能类似insertBefore(); var div = document.getElementsByTagName("div")[0]; ...