![a103879bfd0883c92c3a3066a08f153b.png](https://i-blog.csdnimg.cn/blog_migrate/65333a1970b29d82dbe1c4295f281465.png)
我们在运行一些后端服务时,时常需要同时运行一些定时任务。我们希望定时任务只启动一次,不希望受到gunicorn或flask多进程多线程模式的影响而被启动多次。
不多说了,上代码。等一下,逼乎,真的不考虑给专栏作家一个VIP,唉,文章写的没劲啊。
def scheduler_init(app):
#保证系统只启动一次定时任务,使用文件锁
if platform.system() != 'Windows':
fcntl = __import__("fcntl")
f = open('scheduler.lock', 'wb')
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
scheduler.init_app(app)
scheduler.start()
print("scheduler started.")
except:
pass
def unlock():
fcntl.flock(f, fcntl.LOCK_UN)
f.close()
atexit.register(unlock)
def create_app():
app = Flask(__name__)
app.config.update(
{"SCHEDULER_API_ENABLED": True,
"JOBS": [{"id": "my_job", # 任务ID
"func": "app:cycle_job",#任务位置
"trigger": "interval", #触发器
"minutes": 100, # 时间间隔
"start_date": "2020-05-15 10:00:00"
}
]}
)
scheduler_init(app)
return app
go的锄头挥舞的越来越有力了,python后端蹦跶不了多久了。不必纠结,谁适合用谁,没有哪个语言能在所有领域独占鳌头,各有所长。
这里也提醒一下很多想学python的,你先想想你学了之后用来做什么,不要被那些搞培训班的瞎忽悠了。比如学完了,只想做一些简单的后端服务,那就不建议用python了。其他统计分析、EXCEL操作、可视化之类的还是可以学学,但是建议自学即可。