reboot_saver/background_job.py

82 lines
1.8 KiB
Python
Raw Normal View History

2023-12-28 19:00:29 +01:00
#!/usr/bin/python3
from time import sleep
import psutil
from plyer import notification
def ram_perc():
return psutil.virtual_memory()[2]
def swap_perc():
return psutil.swap_memory()[3]
def get_pwmmu():
pwmmu = ["", 0, 0] # pwmmu = Process With Most Memory Usage
for process in psutil.process_iter():
try:
process_name = process.name()
process_usage = process.memory_info().vms / (1024 * 1024)
process_id = process.pid
if process_usage > pwmmu[1]:
pwmmu = [process_name, process_usage, process_id]
except:
pass
print(pwmmu)
return pwmmu
def kill_process(process_pid):
for process in psutil.process_iter():
if process.pid == process_pid:
process.kill()
def ram_almost_full():
notification.notify(
title="Your RAM is almost full",
message=f"Your RAM usage is over 90%!\nRam usage: {ram_perc()}%\nSwap usage: {swap_perc()}%",
timeout=10,
)
def ram_full():
pwmmu = get_pwmmu()
kill_process(pwmmu[2])
notification.notify(
title="Your memory is full, killed process with most memory usage.",
message=f"Your memory usage was higher than 98%, automatically killed process with most memory usage.\nRam usage: {ram_perc()}%\nSwap usage: {swap_perc()}%\n Killed process: {pwmmu[0]}",
timeout=10,
)
def loop():
2023-12-28 20:10:47 +01:00
warning_cooldown = 0
2023-12-28 19:00:29 +01:00
while True:
ram_usage = ram_perc()
swap_usage = swap_perc()
if ram_usage >= 98 and swap_usage >= 98:
ram_full()
2023-12-29 18:04:55 +01:00
elif ram_usage >= 90 and warning_cooldown == 0:
2023-12-28 19:00:29 +01:00
ram_almost_full()
2023-12-28 20:10:47 +01:00
warning_cooldown = 30
else:
warning_cooldown -= 1
2023-12-29 18:04:55 +01:00
2023-12-28 20:10:47 +01:00
sleep(1)
2023-12-28 19:00:29 +01:00
if __name__ == "__main__":
loop()