简体   繁体   中英

Python Thread that runs at the start of every minute

Hi there i need to implement a thread which runs at the beggining of every minute. The execution flow should look like this.

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

What is the best approach?

Hi I think found a solution, it have some delay as Mr.c explained.

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

Here is a 10secs simulation..

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

Consider using the sched Python module. You say "run at exact time X" or "run after Y seconds have elapsed." It's standard, and supports multiple threads.

Example from the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM