如何在每个时间间隔执行一段代码,而又不影响Python中正常的程序流程? [重复]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

我想在python中执行一个程序,其中我的代码的某些部分每隔10秒检查一次。我尝试了一些建议,但没有解决方案能解决不妨碍程序正常运行的问题。程序进入无限事件循环。我已经发布了程序的最低版本。

这是我尝试过的

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print ("Doing stuff...")
    # do your stuff
    s.enter(10, 1, do_something, (sc,))

s.enter(10, 1, do_something, (s,))
s.run()
for i in range(1, 1000000):
    print("hello")

预期的输出是每10秒沿着Doing stuff面打个招呼。如何在python中实现此目标

python time cron scheduled-tasks scheduler
1个回答
0
投票

我将答案更改为更开箱即用的解决方案,并在代码中留下了一些注释。

编辑:

from threading import Thread
import time

# the variable to check, could be dictionary, user defined class, queue.Queue
# these elements are accessible from other threads
flag = [None]


def check_flag():
    """This is function  checks variable flag value every 0.5 seconds"""
    global flag
    while True:
        if flag[0] == 10:
            print("FLAG = 100 !")
        # should be equal or less than sleep in main thread
        # otherwise can miss moment when flag was equal to 10
        time.sleep(0.5)  


if __name__ == "__main__":
    # start checker thread which runs concurrently with the main thread
    # the checker thread should be daemon, daemon thread stops if main thread finished it's work
    Thread(target=check_flag, daemon=True).start()  

    # some activity in main thread
    for j in range(3):
        for i in range(11):
            flag[0] = i  # change flag value every 0.5 seconds
            time.sleep(0.5)
            print(i)  # print what flag value we have now

我希望代码能够解决问题,随时提出问题。

© www.soinside.com 2019 - 2024. All rights reserved.