Python线程,每分钟开始运行

时间:2014-06-05 10:03:03

标签: python multithreading

您好我需要实现一个在每分钟开始时运行的线程。执行流程应如下所示。

start
sleep until hh.mins.00
do something
sleep until hh.mins.00
do something
sleep ..........
................

最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

嗨我认为找到了一个解决方案,它有一些延迟Mr.c解释。

def run(self):
    while True:
        time.sleep(10-time.time()%10) #sleep to the start of next min
        print time.time()

这是一个10秒的模拟..

1401966250.0
1401966260.01
1401966270.01
1401966280.0
1401966290.01
1401966300.01
1401966310.01
1401966320.01
1401966330.01
1401966340.0
1401966350.01
1401966360.01
1401966370.0
1401966380.01
1401966390.0
1401966400.01
1401966410.0
1401966420.0
1401966430.0
1401966440.0
1401966450.0
1401966460.0

答案 1 :(得分:0)

考虑使用sched Python模块。你说"在确切的时间运行X"或者"在Y秒过后运行。"它是标准的,支持多线程。

fine documentation:

中的示例
>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(): print "From print_time", time.time()
...
>>> def print_some_times():
...     print time.time()
...     s.enter(5, 1, print_time, ())
...     s.enter(10, 1, print_time, ())
...     s.run()
...     print time.time()
...
>>> print_some_times()
930343690.257
From print_time 930343695.274
From print_time 930343700.273
930343700.276