Dec-16-2017, 07:47 PM
Hi coders, The following code is supposed to run once per day. I need help changing the following code so that I can have it run every x hours. Also make sure it "keeps alive" after it has been initiated.
Since I'm new in this forum, I may need some guidance on how to proceed from here.
Thanks!
Since I'm new in this forum, I may need some guidance on how to proceed from here.
Thanks!
from __future__ import print_function from requests import get import json from datetime import datetime,timedelta from time import time,sleep import time as tm from os.path import isfile, join import csv import utils from mysql.connector import connect from urllib import urlencode CREDS = { 'user':'user', 'password':'password', 'host':'host', 'database':'sentxawsdb', 'raise_on_warnings': False } HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36', } def print_wait(hour,minute): now = datetime.now() nxt = datetime.now().replace(hour=hour, minute=minute,second = 0) if ((now-nxt).total_seconds()) > 0 : nxt += timedelta(day = 1 ) while datetime.now() < nxt : dlt = nxt - datetime.now() print('NEXT RUN AT :: {}, IN :: {}'.format(nxt.strftime('%Y-%m-%d %H:%M:%S'),str(dlt).split('.')[0]), sep=' ', end='\r') # No need for sep here, but okay :) sleep(1) print ('*'*60) def read_input(): with open('input.json') as f : inputs = json.load(f) return inputs def insert_data(res): try : cnx = connect(**CREDS) check_tabes(cnx,res) query ='INSERT IGNORE INTO {} (TIME_,VALUE_,WEEK_DAY) VALUES (%s, %s, %s); ' cursor = cnx.cursor() print ('Inserting data ...') for k in res.keys() : cursor.executemany(query.format(k),res[k]) cnx.commit() except Exception as e : print (e) finally : cursor.close() cnx.close() def check_tabes(cnx,res): print ('Checking tables ...') query = ''' CREATE TABLE IF NOT EXISTS {} ( TIME_ VARCHAR(30) PRIMARY KEY, VALUE_ VARCHAR(30), WEEK_DAY VARCHAR(30) )''' cursor = cnx.cursor() for k in res.keys(): cursor.execute(query.format(k)) cnx.commit() def get_last_days(day_numbers=7,offset = 1,date_format = '%m/%d/%Y'): date = datetime.now() time_span = 3600*24*offset return [get_date_before(date,time_span+3600*24*i,date_format) for i in range(day_numbers)] def get_date_before(date,time_span,date_format): delta = date-datetime.fromtimestamp(0) time_span = delta.total_seconds() - time_span return datetime.fromtimestamp(time_span).strftime(date_format)