pythonautomationuser-inactivity

Execute function on user inactivity


At work we have to do our own time management and get controlled from time to time. Because I always forget, when I take my breaks and how long, I decided to write a python script which runs on startup and writes the current time after I haven't moved my mouse or typed on my keyboard for 5 minutes.

import datetime


def writetime():
    t = datetime.datetime.now()

    with open("C:\\Users\\[USER]\\Desktop\\time.txt", 'a') as f:
        f.write('%s \n' % t)

I just don't know, how to execute my function writetime after a certain amount of time elapsed since the last input.


Solution

  • It may not be the cleanest solution but since I am a novice Python programmer I am pretty happy with it. import datetime from ctypes import Structure, windll, c_uint, sizeof, byref import time

    class LASTINPUTINFO(Structure):
        _fields_ = [
            ('cbSize', c_uint),
            ('dwTime', c_uint),
        ]
    
    
    def get_idle_duration():
        lastInputInfo = LASTINPUTINFO()
        lastInputInfo.cbSize = sizeof(lastInputInfo)
        windll.user32.GetLastInputInfo(byref(lastInputInfo))
        millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
        return millis / 1000.0
    
    
    while 1:
        GetLastInputInfo = int(get_idle_duration())
    
        if GetLastInputInfo >= 10:
            start = time.time()
            startTime = datetime.datetime.now()
    
            while GetLastInputInfo >= 10:
                GetLastInputInfo = int(get_idle_duration())
                if GetLastInputInfo < 10:
                    end = time.time()
                    time_elapsed = end - start + 10
                    if time_elapsed >= 10:
                        with open("C:\\Users\\[USER]\\Desktop\\time.txt", 'w') as f:
                            f.write('Pause from ' + str(startTime) + ' to ' + str(
                                datetime.datetime.now()) + '\nDuration: ' + str(time_elapsed))
    

    For testing purposes, I set the time to be marked as absent to 10 seconds. So if you want to make something similar just make sure to change all the 10's to the wished time in seconds