间隔固定时间执行

Code

#!/usr/bin/env python

import sched
import datetime
import time

INTERVAL = 10
scheduler = sched.scheduler(time.time, time.sleep)


def main_loop(sc):
    sc.enter(INTERVAL, 1, main_loop, (sc,))
    print datetime.datetime.now()


def main():
    scheduler.enter(INTERVAL, 1, main_loop, (scheduler,))
    scheduler.run()


if __name__ == '__main__':
    main()

Output

2016-08-31 17:33:11.036000
2016-08-31 17:33:21.037000
2016-08-31 17:33:31.038000
2016-08-31 17:33:41.038000
2016-08-31 17:33:51.039000
2016-08-31 17:34:01.039000
2016-08-31 17:34:11.040000
2016-08-31 17:34:21.040000

每天指定时间执行

Code

#!/usr/bin/env python

import datetime
import time

def do_something():
    print datetime.datetime.now()

def main_loop():
    while True:
        tomorrow = datetime.datetime.replace(datetime.datetime.now() + datetime.timedelta(days=1),
                                             hour=2, minute=0,
                                             second=0, microsecond=0)
        delta = tomorrow - datetime.datetime.now()
        time.sleep(delta.seconds)
        do_something()


if __name__ == '__main__':
    main_loop()

Output



评论

请输入您的评论. 可以使用维基语法: