• python每隔一段时间做一个事情


     1 #!/usr/bin/env python
     2 #coding:utf8
     3 #Author:lsp
     4 #Date:下午2:17:54
     5 #Version:0.1
     6 #Function: 每隔一段时间做一个事情   
     7 from datetime import date, time, datetime, timedelta
     8 
     9 #要做的事情   
    10 def work():
    11   print "hello world."
    12 
    13 def runTask(func, day=0, hour=0, min=0, second=0):
    14   # Init time
    15   now = datetime.now()
    16   strnow = now.strftime('%Y-%m-%d %H:%M:%S')
    17   print "now:",strnow
    18   # First next run time
    19   period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
    20   next_time = now + period
    21   strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
    22   print "next run:",strnext_time
    23   while True:
    24       # Get system current time
    25       iter_now = datetime.now()
    26       iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
    27       if str(iter_now_time) == str(strnext_time):
    28           # Get every start work time
    29           print "start work: %s" % iter_now_time
    30           # Call task func
    31           work()
    32           print "task done."
    33           # Get next iteration time
    34           iter_time = iter_now + period
    35           strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
    36           print "next_iter: %s" % strnext_time
    37           # Continue next iteration
    38           continue
    39 
    40 # runTask(work, min=0.5)
    41 runTask(work(), day=0, hour=0, min=0,second=10)
  • 相关阅读:
    P2813 母舰
    P5367 【模板】康托展开
    P1816 忠诚
    P3865 【模板】ST表
    P1913 L国的战斗之伞兵
    P4939 Agent2
    P1894 [USACO4.2]完美的牛栏The Perfect Stall
    P5017 摆渡车
    P1330 封锁阳光大学
    P5018 对称二叉树
  • 原文地址:https://www.cnblogs.com/lishupeng/p/5590871.html
Copyright © 2020-2023  润新知