Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
change timing on py script
#1
I'm not a coder, but trying to learn. So please bear with me if I'm not expressing myself clearly.

I have two 2.7 .py scripts. One logs into a google trends API, and I believe the other governs how often the first script runs.

I'm showing the code for the one which I believes governs the "timer" of the script. If this is the right code, can you point out the changes I'd need to make so that it runs every 2 hours instead of every 24 hours? 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':'xxxxxxxx',
    'password':'xxxxxxxxx',
    'host':'xxxxxxxxx',
    'database':'xxxxxxxx',
    '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(hour = 3 )

    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*3*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)
Reply
#2
this code has bugs:
the function print_wait uses hour as an argument.
inside that function, the following code:
nxt  += timedelta(hour = 3 )
will cause an 'invalid keyword argument' error (if it ever gets executed) because you
cannot assign a value to an argument

In addition, the code uses sleep which stops execution of the script until timed out.
You'd be better off rewriting, and using sched: https://docs.python.org/2/library/sched.html
Reply
#3
Thank you. I'll need to find a coder who can do that for me because I don't know enough about py to make the necessary changes.
But I am trying to learn so I'll look at the sched documentation.

Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Timing actions with Python dangermaus33 0 981 Apr-19-2022, 10:08 PM
Last Post: dangermaus33
  Inconsistent counting / timing with threading rantwhy 1 1,720 Nov-24-2021, 04:04 AM
Last Post: deanhystad
  Synchronization/Timing Problem quest 5 2,932 Mar-31-2021, 10:26 PM
Last Post: quest
  Timing of a while loop stylingpat 4 6,674 Mar-31-2021, 10:48 AM
Last Post: stylingpat
  Assigning Data from one column to another with different associated timing interval alexafshari 1 1,924 Apr-30-2020, 03:59 PM
Last Post: pyzyx3qwerty
  Change mouse move speed in guibot script rulltartan 1 2,692 Mar-30-2020, 01:51 PM
Last Post: pevogam
  Cannot Change Python script to exe using Pyinstaller omar_mohsen 3 2,338 Dec-19-2019, 01:05 PM
Last Post: buran
  Frequency and timing of psycopg2 commits acecase 0 1,956 Nov-01-2019, 05:50 PM
Last Post: acecase
  Perpetual timing Mark17 3 2,840 Oct-24-2019, 03:46 PM
Last Post: Gribouillis
  Timing input Mark17 2 2,258 Oct-23-2019, 08:25 PM
Last Post: Mark17

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020