code-8
code-8

Reputation: 58662

Execute Python script every hour on MacOS

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?

Upvotes: 8

Views: 26725

Answers (4)

Milor123
Milor123

Reputation: 555

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

Upvotes: 0

patito
patito

Reputation: 540

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

Upvotes: 16

imTachu
imTachu

Reputation: 3809

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)

Upvotes: 2

Querenker
Querenker

Reputation: 2365

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

Upvotes: 2

Related Questions