Skip to content

Instantly share code, notes, and snippets.

@sydney0zq
Created April 18, 2019 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sydney0zq/17b651d64fba4d0c24d826276a7a8f1d to your computer and use it in GitHub Desktop.
Save sydney0zq/17b651d64fba4d0c24d826276a7a8f1d to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 zhou <zhou@Macbook.local>
#
# Distributed under terms of the MIT license.
"""
Water helper program.
"""
import urllib.request as request
import requests
import time
import random
import numpy as np
from datetime import datetime
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("run.log"),
logging.StreamHandler()
])
logger = logging.getLogger(__name__)
DEBUG = False
get_diff_sec = lambda t1, t2: int((t1-t2).total_seconds())
def send_noti_msg():
raise NotImplmentError
def gen_rand_time(hour_range=(8, 22), min_range=(0, 59), freq=8, tomorrow=False):
assert hour_range[1]-hour_range[0]+1 >= freq
Y, M, D = [int(x) for x in datetime.now().strftime('%Y-%m-%d').split('-')]
rand_hour = sorted(np.random.choice([*range(hour_range[0], hour_range[1]+1)], freq, replace=DEBUG))
rand_min = sorted(np.random.choice([*range(min_range[0], min_range[1]+1)], freq, replace=DEBUG))
if tomorrow is False:
L = [datetime(Y, M, D, _hour, _min) for _hour, _min in zip(rand_hour, rand_min)]
else:
L = [datetime(Y, M, D+1, _hour, _min) for _hour, _min in zip(rand_hour, rand_min)]
return L
def loop_worker(L): # Now -> L0, L1, L2 ...
while True:
D = datetime.now()
if len(L) > 0:
time.sleep(get_diff_sec(L[0], D))
if D.hour == L[0].hour and D.minute == L[0].minute:
ret = send_noti_msg()
L.pop(0)
else:
break
if __name__ == "__main__":
L = gen_rand_time()
logger.info("The water helper starts...")
while True:
now_D = datetime.now()
if L[0].day == now_D.day or L[0].day == now_D.day+1:
if now_D < L[0]:
logger.info("The current time is ahead of the time list...")
L = L
elif now_D >= L[-1]:
logger.info("The current time is behind of the time list...")
L = gen_rand_time(tomorrow=True)
else:
logger.info("The current time is in the middle of the time list...")
L = [x for x in L if get_diff_sec(x, now_D) >= 10]
logger.info("The REAL blocking program starts...")
loop_worker(L)
logger.info("Generate time list for the next day...")
L = gen_rand_time(tomorrow=True)
else:
logger.warning("Resetting the weird time list because it's not for today or tomorrow...")
L = gen_rand_time(tomorrow=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment