Skip to content

Instantly share code, notes, and snippets.

@jiaaro
Created July 27, 2012 15:58
Show Gist options
  • Save jiaaro/3188841 to your computer and use it in GitHub Desktop.
Save jiaaro/3188841 to your computer and use it in GitHub Desktop.
Automate life
#!/usr/bin/env python
"""
sleep the specified amount of time
accepts seconds, minutes, hours, days, and years like so:
10 seconds: 10s
15 minutes: 15m
4 hours: 4h
90 days: 90d
1 year: 1y
If you need to subdivide you just have to drop to the next smaller unit.
1d6h is WRONG -- 30h is correct
RANGES
you can as it to sleep randomly between 2h and 4h like so:
defer 2h-4h
the smaller number must be first
"""
import time
import sys
import random
def defer(i, fn=None):
duration = parse_input(i)
time.sleep(duration)
if fn is not None: return fn()
def parse_input(i):
if "-" not in i:
return parse_duration(i)
min, max = i.split("-")
min, max = parse_duration(min), parse_duration(max)
return random.randint(min, max)
def parse_duration(d):
unit = "s"
if d[-1].isalpha():
unit = d[-1]
d = d[:-1]
d = int(d)
return to_sec(unit, d)
def to_sec(unit, duration):
s = lambda x: x
m = lambda x: 60 * s(x)
h = lambda x: 60 * m(x)
d = lambda x: 24 * h(x)
y = lambda x: 365 * d(x)
to_seconds = locals()[unit]
return to_seconds(duration)
if __name__ == "__main__":
defer(sys.argv[1])
#!/bin/bash
#
# Uses defer.
#
# example:
# repeatevery 1h echo "hi mom"
#
# will call `echo "hi mom"` every hour
#
# example 2:
#
# repeatever 2h-6h echo "boo!"
#
# will call `echo "boo!"` every 2 to 6 hours (randomly chosen)
function on_quit () {
kill -2 %1
exit
}
trap "on_quit" SIGQUIT TERM INT
while true ; do
${*:2}
defer $1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment