Python Forum
need coder to change to sched function in script - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Jobs (https://python-forum.io/forum-6.html)
+--- Thread: need coder to change to sched function in script (/thread-6997.html)



need coder to change to sched function in script - kwfreverie - Dec-16-2017

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!

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)



RE: need coder to change to sched function in script - stranac - Dec-16-2017

The code you shared is not responsible for scheduling, it just defines a function that is used to wait until a certain time (and that's a really bad way to do scheduling btw).
Also, it's probably not the best of ideas to share your database credentials on a public forum.


RE: need coder to change to sched function in script - kwfreverie - Dec-16-2017

oops. I wonder if I can edit/delete that post. if not I'll have to change credentials


RE: need coder to change to sched function in script - stranac - Dec-16-2017

I think (not sure at all) that you have to have a certain number of posts to be able to edit them, so I've edited the details out for you.


RE: need coder to change to sched function in script - kwfreverie - Dec-16-2017

thank you so much! Does the code look like it is "writing" data to a mysql database?


RE: need coder to change to sched function in script - stranac - Dec-16-2017

It defines a function insert_data() which writes data to a database, but that function isn't used in this file.
This code doesn't actually do anything, it just defines some constants and functions which are probably imported and used in another file.


RE: need coder to change to sched function in script - buran - Dec-17-2017

A parallel discussion in another sub-section of the forum
https://python-forum.io/Thread-change-timing-on-py-script

I'm not sure if you want to keep this thread in Jobs section.