"Fetch mail periodically"

import os, time

wdays = range(0, 6)         # monday to saturday
hours = range(7, 22)        # "working" hours
repeat = 60 / 3
offset = 45

stopfile = 'maild.stop'     # file whose presence stops maild
userfile = 'maild.user'     # file whose presence indicates to fetch private user mail
nowfile = 'maild.now'       # file whose presence indicates to fetch mail _now_

mins = range(offset % repeat, 60, repeat)

year = month = day = hour = min = sec = wday = 0

def ltime():
    return time.localtime(time.time())

def ctime(t):
    return time.asctime(t)

def dtime(t1, t2):
    return (t1[3] - t2[3]) * 3600 + (t1[4] - t2[4]) * 60 + (t1[5] - t2[5])

def job(t):
    print ctime(t),
    if os.access(userfile, os.F_OK):
        print 'user',
        os.unlink(userfile)
        os.system(r'python mailgate.py -u')
    elif wday < 5 and hour == 11 and min >= mins[-1]:
        print 'priv',
        os.system(r'python mailgate.bat -u')
    else:
        os.system(r'python mailgate.bat')
    print 'done in %3ds' % dtime(ltime(), t)


os.chdir('L:/Python')

t = ltime()
print 'Starting at', ctime(t)
job(t)

while not os.access(stopfile, os.F_OK):

    t = ltime()
    year, month, day, hour, min, sec, wday = t[:7]

    if os.access(nowfile, os.F_OK):
    	os.unlink(nowfile)
    	job(t)
    elif wday in wdays and hour in hours and min in mins:
        job(t)

    time.sleep(60 - ltime()[5]) # wait for the next minute

os.unlink(stopfile)