目标
我有一个用 Python 编写的脚本。
- 连接到数据库
- 插入一些假数据
我的目标是每小时执行一次该脚本。
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
创建任务 >
设置时间表 >
并运行它。
它一直挂在 executing ...
任务到黎明
除此之外,我还尝试了 Task Till Dawn ,并再次
创建一个任务 >
设置时间表 >
并运行它。
结果
似乎没有任何内容插入我的数据库,即使它说 35 次成功执行。它所做的只是弹出我的 database.py
内部 Xcode
窗口。
终端
我运行 python database.py
,它工作得很好,并且插入了数据。
我在想,这是权限问题,但我已经这样做了
sudo chmod a+x database.py
实现这一目标的更好方法是什么?
原文由 code-8 发布,翻译遵循 CC BY-SA 4.0 许可协议
您也可以只使用 crontab:
每隔一小时:
每一分钟:
要查看您的 crontab:
要查看更多选项: