简体   繁体   中英

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. If the previous run completes in eg 120s then I want to execute a new FUNCTION call straight away. If previous run completed in eg 10s then I want to wait 50s before I execute a new FUNCTION call.

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?

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. 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 . and in main function, in while, in else, you put a loops like me

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()

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