简体   繁体   English

让python脚本每小时执行一些功能

[英]Make python script execute some functions every hour

So lets say i have this code:所以可以说我有这段代码:

... ...

connect()
find_links()
find_numbers()

in fact what it does is login to an account,get some numbers and one link: example:实际上它所做的是登录一个帐户,获取一些号码和一个链接:示例:

1.23, 1.32, 32.1, 2131.3 link.com/stats/ 1.23、1.32、32.1、2131.3 link.com/stats/

1.32, 1.41, 3232.1, 21211.3 link.com/stats/ 1.32、1.41、3232.1、21211.3 link.com/stats/

so all i want to do is make these functions run every one hour and then print the time so i can then compare results.I tried:所以我想做的就是让这些函数每隔一小时运行一次,然后打印时间,这样我就可以比较结果。我试过:

sched = BlockingScheduler()
@sched.scheduled_job('interval', seconds=3600 )

def do_that():
     connect()
     find_links()
     find_numbers()
     print(datetime.datetime.now())

but this just executes one time the functions and then just prints the date.但这只执行一次函数,然后只打印日期。

This should call the function once, then wait 3600 second(an hour), call function, wait, ect. 这应该调用一次函数,然后等待3600秒(一个小时),然后调用函数,等待等等。 Does not require anything outside of the standard library. 不需要标准库之外的任何内容。

from time import sleep
from threading import Thread
from datetime import datetime


def func():
    connect()
    find_links()
    find_numbers()
    print(datetime.now())


if __name__ == '__main__':

    Thread(target = func).start()
    while True:
        sleep(3600)
        Thread(target = func).start()

Your code may take some time to run.您的代码可能需要一些时间才能运行。 If you want to execute your function precisely an hour from the previous start time, try this:如果你想从上一个开始时间开始精确执行你的函数,试试这个:

from datetime import datetime
import time


def do_that():
    connect()
    find_links()
    find_numbers()
    print(datetime.now())


if __name__ == '__main__':

    starttime = time.time()
    while True:
        do_that()
        time.sleep(3600.0 - ((time.time() - starttime) % 3600.0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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