Created
October 13, 2012 11:26
-
-
Save pbanaszkiewicz/3884218 to your computer and use it in GitHub Desktop.
Turn the computer off after specified time. Show notifications.
This file contains hidden or 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
#!/usr/bin/env python | |
# coding: utf-8 | |
import os | |
import datetime | |
import time | |
import pynotify | |
MAX_UPTIME = 60 * 60 # in seconds: 1 hour | |
def check_time_diff(ref_time, difference=10): | |
""" | |
Compare current time with reference time. Epsilon is set for 10 seconds. | |
:param ref_time: reference time, which is compared with current time. | |
:param difference: max possible difference between compared times (in | |
seconds). 10 seconds by default. | |
""" | |
now = datetime.datetime.now() | |
diff = abs(now - ref_time) | |
if diff.seconds <= difference or now > ref_time: | |
return True | |
else: | |
return False | |
def main(start_time, max_usage_time): | |
""" | |
Show notifications 5 minutes, 1 minute, 10 seconds before shutdown. | |
:param start_time: the time when the countdown should be started. Usually | |
it's datetime.datetime.now() | |
:param max_usage_time: time (in seconds) when to shutdown. Should be | |
positive (obviously) and at least 5 minutes. | |
""" | |
max_usage_time = datetime.timedelta(seconds=max_usage_time) | |
five_min = start_time + max_usage_time - datetime.timedelta(seconds=5 * 60) | |
one_min = start_time + max_usage_time - datetime.timedelta(seconds=1 * 60) | |
max_usage_time = start_time + max_usage_time | |
five_min_mark = False | |
one_min_mark = False | |
while 1: | |
time.sleep(5) | |
if not five_min_mark and check_time_diff(five_min): | |
five_min_mark = True | |
notification = pynotify.Notification("UWAGA!", "Komputer zostanie" | |
" zamkniÄty za 5 minut.") | |
notification.show() | |
continue | |
if not one_min_mark and check_time_diff(one_min): | |
one_min_mark = True | |
notification = pynotify.Notification("UWAGA!", "Komputer zostanie" | |
" zamkniÄty za 1 minutÄ.") | |
notification.show() | |
continue | |
if check_time_diff(max_usage_time): | |
notification = pynotify.Notification("UWAGA!", "Komputer zostanie" | |
" zamkniÄty za 10 sekund.") | |
notification.show() | |
time.sleep(10) | |
return True | |
# just in case | |
return False | |
def shutdown(): | |
""" | |
Perform shutdown of the system. Shouldn't need root priviledges. | |
The scripts needs +s chmod flag to run this command. | |
""" | |
os.system("shutdown now -h") | |
if __name__ == '__main__': | |
start_time = datetime.datetime.now() | |
pynotify.init("ShutdownNowTimeApp") | |
main(start_time, MAX_UPTIME) | |
shutdown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment