-
-
Save Raka-loah/b33f666fa08e321fb534c5d7de1f9d3e to your computer and use it in GitHub Desktop.
Log a timestamp when memory usage is over 90%, per minute.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from apscheduler.schedulers.blocking import BlockingScheduler | |
# APScheduler库用于定时执行,BlockingScheduler为前台运行的定时器 | |
from psutil import virtual_memory | |
from datetime import datetime | |
def main(): | |
memory = virtual_memory() | |
occ_rate = memory.used / memory.total | |
# 若内存占用率大于90%: | |
if occ_rate > 0.9: | |
# With关键字实现写入文件并自动关闭,a+模式为附加到文件最后,若文件不存在新建 | |
with open('memory_log.txt', mode='a+') as f: | |
# f-string格式化字符串写起来更短 | |
f.write(f'{datetime.now():%Y-%m-%d %H:%M:%S}: {occ_rate*100:.2f}%\n') | |
if __name__ == '__main__': | |
# 新建一个定时器 | |
scheduler = BlockingScheduler() | |
# 加入定时运行的任务,间隔1分钟执行一次 | |
scheduler.add_job(main, 'interval', minutes=1) | |
# 定时器开跑 | |
scheduler.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment