如何在Linux启动时自动启动和停止Python APScheduler (我的例子是Centos),并在关机时停止它?
我可以在linux启动时启动python脚本,但是如何停止它呢?(还记得PID吗?)
我想知道这是不是应该这样做,因为我想要有一个简单的部署,这样开发人员就可以在测试/生产中轻松地更新文件并重新启动调度程序,而不会成为根目录,这样他们就可以启动/停止服务。
目前我已经使用tmux启动/停止了调度程序,这是有效的,但我似乎找不到一个好的方法来改进它,以便在服务器启动/停止期间自动启动/停止,并在部署期间轻松更新:(
发布于 2018-01-30 02:20:44
通常创建一个扩展名为.pid的文件来保存进程PID。然后,您需要注册一个信号处理程序以干净地退出,并确保在退出时删除.pid文件。
例如:
#!/usr/bin/env python
import signal
import atexit
import os
PID_FILE_PATH = "program.pid"
stop = False
def create_pid_file():
# this creates a file called program.pid
with open(PID_FILE_PATH, "w") as fhandler:
# and stores the PID in it
fhandler.write(str(os.getpid()))
def sigint_handler(signum, frame):
print("Cleanly exiting")
global stop
# this will break the main loop
stop = True
def exit_handler():
# delete PID file
os.unlink(PID_FILE_PATH)
def main():
create_pid_file()
# this makes exit_handler to be called automatically when the program exists
atexit.register(exit_handler)
# this makes sigint_handler to be called when a signal SIGTERM
# is sent to the process, e.g with command: kill -SIGTERM $PID
signal.signal(signal.SIGTERM, sigint_handler)
while not stop:
# this represents your main loop
pass
if __name__ == "__main__":
main()https://stackoverflow.com/questions/48506824
复制相似问题