Python 以一个指定的间隔定时循环执行任务

简介:

程序功能:指定一个或者同时多个固定的延迟(例如,5mins, 1hour,1 day, 1 week),程序按照这个指定的延迟定时循环执行某个work




from datetime import date, time, datetime, timedelta


def work():

   print "hello world."


def runTask(func, day=0, hour=0, min=0, second=0):

   # Init time

   now = datetime.now()

   strnow = now.strftime('%Y-%m-%d %H:%M:%S')

   print "now:",strnow

   # First next run time

   period = timedelta(days=day, hours=hour, minutes=min, seconds=second)

   next_time = now + period

   strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')

   print "next run:",strnext_time

   while True:

       # Get system current time

       iter_now = datetime.now()

       iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')

       if str(iter_now_time) == str(strnext_time):

           # Get every start work time

           print "start work: %s" % iter_now_time

           # Call task func

           func()

           print "task done."

           # Get next iteration time

           iter_time = iter_now + period

           strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')

           print "next_iter: %s" % strnext_time

           # Continue next iteration

           continue


# runTask(work, min=0.5)

runTask(work, day=1, hour=2, min=1)



本文转自 pgmia 51CTO博客,原文链接:http://blog.51cto.com/heyiyi/1365908

相关文章
|
1月前
|
Python
python用户输入和while循环(四)
python用户输入和while循环(四)
26 1
|
1月前
|
安全 Python
python用户输入和while循环(二)
python用户输入和while循环(二)
18 0
|
1月前
|
Python
在Python中while循环
在Python中while循环
18 1
|
1月前
|
Python
python用户输入和while循环(一)
python用户输入和while循环(一)
17 0
|
1月前
|
数据采集 存储 Java
「多线程大杀器」Python并发编程利器:ThreadPoolExecutor,让你一次性轻松开启多个线程,秒杀大量任务!
「多线程大杀器」Python并发编程利器:ThreadPoolExecutor,让你一次性轻松开启多个线程,秒杀大量任务!
|
1月前
|
存储 索引 Python
python用户输入和while循环(五)
python用户输入和while循环(五)
17 0
|
1月前
|
Python
python用户输入和while循环(三)
python用户输入和while循环(三)
19 0
|
1月前
|
Python
Python-循环
Python-循环
19 1
|
1月前
|
存储 算法 索引
python用户输入和while循环(六)
python用户输入和while循环(六)
18 0
|
1月前
|
存储 索引 Python
python用户输入和while循环(七)
python用户输入和while循环(七)
16 0

热门文章

最新文章