Search code examples
pythonpsutil

How would you use psutil to kill idle processes that exceed over a duration amount of time?


I'm trying to use psutil to kill a specific process when it's not in use / hasn't been interacted/touched with for a long time, here's what I have currently:

import psutil

for proc in psutil.process_iter():
    if 'Application.exe' in proc.name():
        proc.kill()

This code only kills the process if it finds it by the name - how would I use psutil to kill idle processes that have exceeded a certain duration?


Solution

  • you can use create_time() to get the process creation time.

    Your code should look like:

    import psutil
    import time
    
    for proc in psutil.process_iter():
        if 'Application.exe' in proc.name():
            proc_duration = (time.time() - proc.create_time()) % 60
            if proc_duration > 25.0:
                proc.kill()
    

    You can also get CPU Usage and other process data using psutil. Hope it helps!