简体   繁体   English

python每隔n秒执行一次函数等待完成

[英]python execute function every n seconds wait for completion

I want to execute FUNCTION periodically every 60 seconds, but I don't want to execute FUNCTION again IF the previous run has not completed yet.我想每 60 秒定期执行一次 FUNCTION,但如果上次运行尚未完成,我不想再次执行 FUNCTION。 If the previous run completes in eg 120s then I want to execute a new FUNCTION call straight away.如果上一次运行在例如 120 秒内完成,那么我想立即执行一个新的 FUNCTION 调用。 If previous run completed in eg 10s then I want to wait 50s before I execute a new FUNCTION call.如果上一次运行在例如 10 秒内完成,那么我想在执行新的 FUNCTION 调用之前等待 50 秒。

Please see my implementation below.请在下面查看我的实现。

Can I achieve it with eg subprocess.run or some timeloop library so that the implementation would be much cleaner?我可以使用例如 subprocess.run 或一些 timeloop 库来实现它,以便实现更清晰吗?

import time


def hello(x):
    # some logic here
    # execution could take any time between e.g. <10s, 120s>


def main(ii):
    while True:
        start = int(time.time())

        try:
            val = next(ii)
        except StopIteration as ex:
            return None

        else:
            hello(val)

            run_time_diff = int(time.time()) - start

            if run_time_diff < 60:
                time.sleep(60 - run_time_diff)


ii = iter(list[[...],[...],...[...]])
main(ii=ii)

maybe apsheduler could help you.也许 apsheduler 可以帮助你。 But if your job wil run more then waiting time, it could be skipped.但是,如果您的工作运行时间超过等待时间,则可以跳过它。 In this case you can increase number of workers.在这种情况下,您可以增加工人数量。

import datetime
import time

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()

def some_job():
    time.sleep(5)
    print(f"{datetime.datetime.utcnow()}: Every 10 seconds")


job = scheduler.add_job(some_job, 'interval', seconds=10, max_instances=1)

scheduler.start()
try:
    while True:
        time.sleep(1)
finally:
    scheduler.shutdown()

in hello, you put return 0 .你好,你把return 0 and in main function, in while, in else, you put a loops like me在 main 函数中,在 while 中,在 else 中,你像我一样放置了一个循环

x = hello(val)
if x = 0:
# Your custom code after function will be excute
  main()
else:
# Re-excute the function if it not work
  hello(val)

But Im not sure my x when define, it will excute hello()但我不确定我的x在定义时,它会执行hello()

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

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