python fcntlファイルロック
2345 ワード
このモジュールはunixシステムにしかありません.windowsにはありません.
ドキュメントのアドレス:
https://docs.python.org/3.7/library/fcntl.html
https://www.docs4dev.com/docs/zh/python/3.7.2rc1/all/library-fcntl.html
マルチプロセスサンプルプログラム
fcntl詳細パラメータ
gunicorn flask-apscheduler繰返し実行問題の解決
ドキュメントのアドレス:
https://docs.python.org/3.7/library/fcntl.html
https://www.docs4dev.com/docs/zh/python/3.7.2rc1/all/library-fcntl.html
マルチプロセスサンプルプログラム
import fcntl
import os
import time
from multiprocessing import Pool
def worker():
print('task: %s' % os.getpid())
try:
f = open('scheduler.lock', 'wb')
''' , , '''
fcntl.flock(f, fcntl.LOCK_EX)
print('I am get file %s' % os.getpid())
time.sleep(10)
''' '''
fcntl.flock(f, fcntl.LOCK_UN)
f.close()
except Exception as e:
print('file is already locked: %s' % os.getpid())
if __name__ == '__main__':
p = Pool(4)
for i in range(5):
p.apply_async(worker)
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
fcntl詳細パラメータ
'''f ,operator '''
fcntl.flock(f, operator)
fcntl.LOCK_SH ' '
fcntl.LOCK_EX ' '
fcntl.LOCK_NB ' —— , , , 。LOCK_NB LOCK_SH LOCK_NB (|) 。 fcntl.flock (f,fcntl.LOCK_EX|fcntl.LOCK_NB)'
fcntl.LOCK_UN ' '
gunicorn flask-apscheduler繰返し実行問題の解決
from flask import Flask
from service.extensions import scheduler
import logging
from logging.handlers import RotatingFileHandler
import os
import fcntl, atexit
basedir = os.path.abspath('')
def create_app():
app = Flask(__name__)
f = open("scheduler.lock", "wb")
try:
''' '''
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
register_apscheduler(app)
except Exception as e:
pass
def unlock():
fcntl.flock(f, fcntl.LOCK_UN)
f.close()
''' , , , '''
atexit.register(unlock)
return app
def register_apscheduler(app):
scheduler.init_app(app)
from service import aliyuncron
scheduler.start()
app = create_app()
@app.route('/')
def index():
return 'Hello World!'