AlexAgla
AlexAgla

Reputation: 63

Python automatic pc restart

hello all I have writen a .pyw script to automatically restart my computer if I have been idle for x amount of seconds. For some reason the script just returns the value 0.328 for idleTime instead of actually counting the seconds ive been idle. Not really sure where this problem lies so here is my code

import os
import datetime
from ctypes import Structure, windll, c_uint, sizeof, byref

#Script will automatically restart computer at 4 am unless user 
#hits abort button.

os.system("start C:/Users/alexa/Desktop/test.txt")

#checks how long user has been idle for
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


idleTime = get_idle_duration()

while(idleTime <= 30):
    print(idleTime)
    if(idleTime >= 30):
        os.system("shutdown")

Upvotes: 1

Views: 102

Answers (3)

Tomas
Tomas

Reputation: 111

As said by Pythonista, you are not updating python time, but since I cant yet post comment I am including solution as new answer


while(True):
    idleTime = get_idle_duration()
    print(idleTime)
    if(idleTime >= 30):
        os.system("shutdown") 

However to consume resources it is good idea to import time and add

time.sleep(1)

at the end of while loop so it only checks once a second...

Upvotes: 1

Nicholas Shaffer
Nicholas Shaffer

Reputation: 80

Pythonista is correct. Also you are returning millis variable divided by 1000. This will make your execution of restart very lengthy because it will take 1000x's longer then the set duration to restart. I suggest you test this program without the division in the return and try something around 5 minutes and see what you get as a result.

Upvotes: 0

Pythonista
Pythonista

Reputation: 11645

You never update idleTime you set it once and then execute a while loop....

Upvotes: 2

Related Questions