7

Goal

I have a script written in Python.

  1. connect to database
  2. insert some fake data

My goal is execute that script every hour.


database.py

#!/usr/bin/python


import MySQLdb
import random
import requests
import time


db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="root",         # your username
                     passwd="*********",  # your password
                     db="db-local")       # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# The first line is defined for specified vendor
mac = [ 0x00, 0x24, 0x81,
    random.randint(0x00, 0x7f),
    random.randint(0x00, 0xff),
    random.randint(0x00, 0xff) ]

device_mac =  ':'.join(map(lambda x: "%02x" % x, mac))
cpe_mac = '000D6766F2F6'

url = "https://randomuser.me/api/"
data = requests.get(url).json()
firstname = data['results'][0]['user']['name']['first']
lastname = data['results'][0]['user']['name']['last']
email = data['results'][0]['user']['email']
gender = data['results'][0]['user']['gender']

age_range_options = [">15", "15-25", "25-40","40+"]
age_range = random.choice(age_range_options)

ip = '10.10.10.10'
host_name = 'cron.job'
visit_count = 1
created_at = time.strftime('%Y-%m-%d %H:%M:%S')
updated_at = time.strftime('%Y-%m-%d %H:%M:%S')

sql = ('''INSERT INTO visitors (device_mac,cpe_mac,firstname, lastname, email, gender, age_range,ip,host_name,visit_count,created_at, updated_at) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''')

args = (device_mac,cpe_mac, firstname, lastname, email, gender, age_range,ip, host_name,visit_count, created_at, updated_at)
cur.execute(sql,args)
db.commit()


# for record in records:
# print records

db.close()

CronniX

I did some researches, and people suggested a bunch of apps to do that.

So I've tried downloaded/installed CronniX

create a task > set the schedule > and run it.

enter image description here

It kept hanging on executing ...


Task Till Dawn

In addition to that, I've also tried Task Till Dawn, and again

create a task > set the schedule > and run it.

Result

enter image description here

Nothing seem to insert to my database, even it said 35 succesfully executions. All it did was pop up my database.py inside Xcode window.


Terminal

I run python database.py, It works perfectly fine, and data get inserted.


I was thinking that, it was the permission issue, but I already did

sudo chmod a+x database.py


What's the better way to achieve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
code-8
  • 54,650
  • 106
  • 352
  • 604
  • Did you tried cron? Sometimes simple solutions work best, and you're already using the terminal... – Rafael Santos Mar 27 '16 at 16:21
  • If I use cron how do I set/configure it to run every 60 minutes. Please kindly advise, in the meantime, I'll read up on `cron`. Thanks for your suggestion. – code-8 Mar 27 '16 at 16:22
  • Just do it all in python. Use a thread and sleep it for an hour. – OneCricketeer Mar 27 '16 at 16:23
  • Does `./database.py` work from terminal, without python? And `/usr/bin/python database.py` – xvan Mar 27 '16 at 16:24
  • @cricket_007 : If I do it all in python, I will have to open up terminal, and type `python database.py`. I'm looking for something, that do it automatically in the background. Please correct me, if missed anything here. – code-8 Mar 27 '16 at 16:26
  • @xvan : `database.py` is inside my `Dekstop\python\database.py` . Just out of curiosity, will path matter ? – code-8 Mar 27 '16 at 16:28
  • If the shebang! isnt't properly set (/usr/bin/python doesn't exists or you have two pythons) your os won't know how to execute your script. Again, did you try what I asked? If it doesn't work from terminal won't work from cron. Try calling the script by itself, without python, from the terminal. – xvan Mar 27 '16 at 16:38
  • Re: "All it did was pop up my database.py inside Xcode window." - This is because Task Till Dawn does the same as double-clicking the database.py file in a Finder window, and the default action is to open it in XCode. To make it work as you want, you can create an Automator Application that runs the shell script (or use https://sveinbjorn.org/platypus), then have Task Till Dawn open that file/Application instead. – Motin May 04 '20 at 08:21

4 Answers4

15

You can also just use crontab:

Every hour:

crontab 0 * * * * /path/to/script

Every minute:

crontab * * * * * /path/to/script

To see your crontabs:

crontab -l

To see further options:

man crontab
patito
  • 530
  • 2
  • 13
2

You can use crontab and I think it is already installed on OSX?

Open a Terminal and run crontab -e. This should open an Editor. There you can type

@hourly /usr/bin/python database.py

Querenker
  • 2,242
  • 1
  • 18
  • 29
2

According to Rafael Santos advice, you could use a cron simply like this:

You type: crontab -e and add this line:

0 * * * * /path/to/your/script

It will run your script ever hour. Or if you are using Django you can use Celery that does the same thing. (It has a crontab type)

imTachu
  • 3,759
  • 4
  • 29
  • 56
0

take the time run, and sum +1h, and then each 5s verify current, with the old time+1h

import datetime
import time
mytime= datetime.datetime.now()
currenttime= str(datetime.datetime.time(mytime))
currenttime = currenttime.split(':')
data = list(currenttime)
data[0] = str(int(data[0])+1) # [0] is the first part of 00:00:00, and +1 is the sum for the hour part
print data
print currenttime
while True:
    mytime= datetime.datetime.now()
    currenttime= str(datetime.datetime.time(mytime))
    currenttime = currenttime.split(':')
    # Note: if want test code, delete the while and time.sleep()
    time.sleep(5)
    if data==currenttime:
        exit(0)

you should add this as functions because my code is ugly xDD

Milor123
  • 537
  • 4
  • 20