py-py’s blog

何か書くよ

cronで動かすpythonの重複起動制御

import fcntl
from datetime import datetime


def main():
    with open(__file__, "+a") as Lockfile:
        try:
            fcntl.flock(Lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            while True:
                now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                print(f"{now}: hi")
        except Exception as e:
            print(f"{e} 重複エラーです")


if __name__ == "__main__":
    main()