Python实现定时精度可调节的定时器

本文实例为大家分享了Python实现定时精度可调节的定时器,供大家参考,具体内容如下

# -* coding: utf-8 -*- 

import sys
import os
import getopt
import threading
import time 

def Usage():
  usage_str = '''''说明:
  \t定时器
  \timer.py -h 显示本帮助信息,也可以使用--help选项
  \timer.py -d num 指定一个延时时间(以毫秒为单位)
  \t          也可以使用--duration=num选项
  '''
  print(usage_str) 

def args_proc(argv):
  '''''处理命令行参数'''
  try:
    opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration='])
  except getopt.GetoptError as err:
    print('错误!请为脚本指定正确的命令行参数。\n')
    Usage()
    sys.exit(255) 

  if len(opts) < 1:
    print('使用提示:缺少必须的参数。')
    Usage()
    sys.exit(255) 

  usr_argvs = {}
  for op, value in opts:
    if op in ('-h', '--help'):
      Usage()
      sys.exit(1)
    elif op in ('-d', '--duration'):
      if int(value) <= 0:
        print('错误!指定的参数值%s无效。\n' % (value))
        Usage()
        sys.exit(2)
      else:
        usr_argvs['-d'] = int(value)
    else:
      print('unhandled option')
      sys.exit(3) 

  return usr_argvs 

def timer_proc(interval_in_millisecond):
  loop_interval = 10   # 定时精度,也是循环间隔时间(毫秒),也是输出信息刷新间隔时间,它不能大于指定的最大延时时间,否则可能导致无任何输出
  t = interval_in_millisecond / loop_interval
  while t >= 0:
    min = (t * loop_interval) / 1000 / 60
    sec = (t * loop_interval) / 1000 % 60
    millisecond = (t * loop_interval) % 1000
    print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t')
    time.sleep(loop_interval / 1000)
    t -= 1
  if millisecond != 0:
    millisecond = 0
    print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t')
  print() 

# 应用程序入口
if __name__ == '__main__':
  usr_argvs = {}
  usr_argvs = args_proc(sys.argv)
  for argv in usr_argvs:
    if argv in ( '-d', '--duration'):
      timer_proc(usr_argvs[argv])
    else:
      continue

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

您可能感兴趣的文章:

  • Python定时器实例代码
  • python定时器(Timer)用法简单实例
  • wxPython定时器wx.Timer简单应用实例
  • python使用线程封装的一个简单定时器类实例
  • 用Python编写简单的定时器的方法
  • python通过线程实现定时器timer的方法
  • python单线程实现多个定时器示例
  • python定时器使用示例分享
(0)

相关推荐

  • Python定时器实例代码

    在实际应用中,我们经常需要使用定时器去触发一些事件.Python中通过线程实现定时器timer,其使用非常简单.看示例: import threading def fun_timer(): print('Hello Timer!') timer = threading.Timer(1, fun_timer) timer.start() 输出结果: Hello Timer! Process finished with exit code 0 注意,只输出了一次,程序就结束了,显然不是我们想要的结果

  • python通过线程实现定时器timer的方法

    本文实例讲述了python通过线程实现定时器timer的方法.分享给大家供大家参考.具体分析如下: 这个python类实现了一个定时器效果,调用非常简单,可以让系统定时执行指定的函数 下面介绍以threading模块来实现定时器的方法. 使用前先做一个简单试验: import threading def sayhello(): print "hello world" global t #Notice: use global variable! t = threading.Timer(5

  • wxPython定时器wx.Timer简单应用实例

    本文实例讲述了wxPython定时器wx.Timer简单应用.分享给大家供大家参考.具体如下: # -*- coding: utf-8 -*- ######################################################## ## 这是wxPython定时器wx.Timer的简单应用 ## testwxTimer1.pyw ######################################################## import wx impo

  • 用Python编写简单的定时器的方法

    下面介绍以threading模块来实现定时器的方法. 首先介绍一个最简单实现: import threading def say_sth(str): print str t = threading.Timer(2.0, say_sth,[str]) t.start() if __name__ == '__main__': timer = threading.Timer(2.0,say_sth,['i am here too.']) timer.start() 不清楚在某些特殊应用场景下有什么缺陷

  • python使用线程封装的一个简单定时器类实例

    本文实例讲述了python使用线程封装的一个简单定时器类.分享给大家供大家参考.具体实现方法如下: from threading import Timer class MyTimer: def __init__(self): self._timer= None self._tm = None self._fn = None def _do_func(self): if self._fn: self._fn() self._do_start() def _do_start(self): self.

  • python单线程实现多个定时器示例

    单线程实现多个定时器 NewTimer.py 复制代码 代码如下: #!/usr/bin/env python from heapq import *from threading import Timerimport threadingimport uuidimport timeimport datetimeimport sysimport math global TimerStampglobal TimerTimes class CancelFail(Exception):    pass c

  • python定时器(Timer)用法简单实例

    本文实例讲述了python定时器(Timer)用法.分享给大家供大家参考.具体如下: # encoding: UTF-8 import threading #Timer(定时器)是Thread的派生类, #用于在指定时间后调用一个方法. def func(): print 'hello timer!' timer = threading.Timer(5, func) timer.start() 该程序可实现延迟5秒后调用func方法的功能. 希望本文所述对大家的Python程序设计有所帮助.

  • python定时器使用示例分享

    复制代码 代码如下: class SLTimer(multiprocessing.Process):    #from datetime import datetime    #import time def __init__(self, target=None, args=(), kwargs={},date=None,time=None):        '''\        @param date 1900-01-01        @param time 00:00:00       

  • Python实现定时精度可调节的定时器

    本文实例为大家分享了Python实现定时精度可调节的定时器,供大家参考,具体内容如下 # -* coding: utf-8 -*- import sys import os import getopt import threading import time def Usage(): usage_str = '''''说明: \t定时器 \timer.py -h 显示本帮助信息,也可以使用--help选项 \timer.py -d num 指定一个延时时间(以毫秒为单位) \t 也可以使用--d

  • 基于Python实现定时自动给微信好友发送天气预报

    效果图 from wxpyimport * import requests from datetimeimport datetime import time from apscheduler.schedulers.blockingimport BlockingScheduler#定时框架 bot = Bot(cache_path=True) tuling = Tuling(api_key=你的api')#机器人api def send_weather(location): #准备url地址 pa

  • python循环定时中断执行某一段程序的实例

    问题说明 最近在写爬虫,由于单个账号访问频率太高会被封,所以需要在爬虫执行一段时间间隔后自己循环切换账号 所以就在想,有没有像单片机那样子设置一个定时中断,再定义一个中断入口,这样子每隔一段时间执行一次中断 当然不能用sleep,这样子整个进程就停在这了,而不是接着爬数据 解决方法 用到threading的Timer,也类似单片机那样子,在中断程序中再重置定时器,设置中断,python实例代码如下 import threading import time def change_user(): p

  • Python实现定时检测网站运行状态的示例代码

    通过定时的检测网站的状态,通常检测地址为网站的域名,如果链接的状态码不是200,那么,就将对其进行下线处理,在特定时间后对其进行二次探测状态,如果符合将其上线,以前使用的创宇云的监控,但是功能比较单一,无法满足需求,近期使用Python来实现这一功能,后期将编写监控模块,并进行代码开源或搭建公共服务器. 本次抒写的是链接状态码获取,可以一应用在网站监控,友情链接监控等方面,及时作出提醒预警.状态处理等,方便网站优化.本次使用了python的requests.datatime.BlockingSc

  • 利用Python实现定时程序的方法

    目录 定时器概念 实现一个简单的定时程序 方案一 方案二 定时器概念 什么是定时器呢?它是指从指定的时刻开始,经过一个指定时间,然后触发一个事件,用户可以自定义定时器的周期与频率. 实现一个简单的定时程序 方案一 在 Python 中,如何定义一个定时器函数呢?我们先看第一种方法.假设我们需要执行一个函数userCountFunc,这个函数需要每隔一个小时被执行一次.那么,我们可以这样写: def main(): startCronTask(userCountFunc, minutes=60)

  • Python实现定时监测网站运行状态的示例代码

    先说一下为啥会写这段代码,大家在浏览网页的时候都会看到友情链接,友情链接里面的链接地址,如果不能正常的,那么在SEO方面会有影响,如何及时的发现无效或者错误的链接并及时对其进行下线处理,这是一个至关重要的问题. 通过定时的监测网站的状态,通常监测地址为网站的域名,如果链接的状态码不是200,那么,就将对其进行下线处理,在特定时间后对其进行二次探测状态,如果符合将其上线,以前使用的创宇云的监控,但是功能比较单一,无法满足需求,近期使用Python来实现这一功能,后期将编写监控模块,并进行代码开源或

  • python实现定时同步本机与北京时间的方法

    本文实例讲述了python实现定时同步本机与北京时间的方法.分享给大家供大家参考.具体如下: 这段python代码首先从www.beijing-time.org上获取标准的北京时间,然后同步获取的北京时间到本地 # -*- coding: utf-8 -*- import time,httplib import threading def getBeijinTime(): try: conn = httplib.HTTPConnection("www.beijing-time.org"

  • python实现定时自动备份文件到其他主机的实例代码

    定时将源文件或目录使用WinRAR压缩并自动备份到本地或网络上的主机 1.确保WinRAR安装在默认路径或者把WinRAR.exe添加到环境变量中 2.在代码里的sources填写备份的文件或目录,target_dir填写备份目的目录 3.delete_source_file为备份完后是否删除源文件(不删除子文件夹) 4.备份成功/失败后生成备份日志 按照格式,填写源目的: sources = [r'E:\目录1', r'E:\目录2\b.txt'] #例:= [ r'E:\test\1234.

  • Python实现定时备份mysql数据库并把备份数据库邮件发送

    一.先来看备份mysql数据库的命令 mysqldump -u root --password=root --database abcDataBase > c:/abc_backup.sql 二.写Python程序 BackupsDB.py #!/usr/bin/python # -*- coding: UTF-8 -*- ''''' zhouzhongqing 备份数据库 ''' import os import time import sched import smtplib from em

随机推荐