Skip to content

Instantly share code, notes, and snippets.

@pbanaszkiewicz
Created October 13, 2012 11:26
Show Gist options
  • Save pbanaszkiewicz/3884218 to your computer and use it in GitHub Desktop.
Save pbanaszkiewicz/3884218 to your computer and use it in GitHub Desktop.
Turn the computer off after specified time. Show notifications.
#!/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