2018-4-27 python實現systemd進程后台運行任務


 

   這個功能非常實用啊,這樣子可以通過ansible推送agent到客戶端上,然后守護進程進行周期性采集數據,返回給服務端,server端再前端展示數據。

 

[root@k8s-master py]# cat /root/py/test.py  # 更改此文件,要重啟systemd restart test.service服務才行

 

#!/usr/bin/env python # -*- coding=utf-8 -*-
import time filepath = '/root/py/test_systemd' # 文件路徑
fm = '%Y-%m-%d %X'
def get_time(): while 1: nowtime = time.strftime(fm, time.localtime()) with open(filepath, 'a') as fp:  # a模式就代表寫形式的追加
 fp.write(nowtime) fp.write('\n') time.sleep(5) if __name__ == '__main__': get_time()

 

[root@k8s-master py]# touch /root/py/test_systemd
[root@k8s-master py]# cat /etc/systemd/system/test.service
[Unit]
Description = test daemon
After = rc.local.service

[Service]
Type = simple
User = root
Group = root
ExecStart = /usr/bin/python /root/py/test.py
StartLimitInterval = 30min

[Install]
WantedBy = multi-user.target


[root@k8s-master py]# systemctl start test.service && systemctl enable test.service
[root@k8s-master py]# ps -ef |grep python
[root@k8s-master py]# tail -f /root/py/test_systemd
2018-04-23 11:41:15
2018-04-23 11:41:20
2018-04-23 11:41:25
2018-04-23 11:41:30

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM