【问题标题】:Execute Python Script Every Hour on MacOS在 MacOS 上每小时执行一次 Python 脚本
【发布时间】:2016-07-14 23:01:06
【问题描述】:

目标

我有一个用 python 编写的脚本。

  1. 连接数据库
  2. 插入一些虚假数据

我的目标是每小时执行一次该脚本。


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

我做了一些研究,人们建议了一堆应用程序来做到这一点。

所以我尝试下载/安装 CronniX

创建一个任务> 设置计划> 并运行它。

它一直挂在executing ...


任务到黎明

除此之外,我还尝试了Task Till Dawn,并且再次尝试

创建一个任务> 设置计划> 并运行它。

结果

似乎没有任何东西插入到我的数据库中,即使它说成功执行了 35 次。它所做的只是在Xcode 窗口中弹出我的database.py


终端

我运行python database.py,它工作得非常好,并且数据被插入。


我在想,这是权限问题,但我已经这样做了

sudo chmod a+x database.py


我错过了什么?实现这一目标的更好方法是什么?

任何建议/提示将不胜感激!

【问题讨论】:

  • 你试过cron吗?有时简单的解决方案效果最好,而您已经在使用终端...
  • 如果我使用 cron 我如何设置/配置它以每 60 分钟运行一次。请告知,与此同时,我会阅读cron。感谢您的建议。
  • 只需在 python 中完成。使用线程并将其休眠一个小时。
  • ./database.py 是否可以在没有 python 的情况下从终端工作?还有/usr/bin/python database.py
  • @cricket_007 :如果我在 python 中完成这一切,我将不得不打开终端,然后输入 python database.py。我正在寻找一些东西,它会在后台自动执行。如果在这里遗漏了什么,请纠正我。

标签: python macos cron cron-task


【解决方案1】:

你也可以只使用 crontab:

每小时:

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

每分钟:

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

要查看您的 crontab:

crontab -l

查看更多选项:

man crontab

【讨论】:

  • 我可以将它减少到一分钟以进行测试以验证它是否有效?这会工作crontab * * * * * /path/to/script 吗?
  • 酷,现在试试。谢谢。 :)
  • 我在尝试crontab 0 * * * * /path/to/script 时得到crontab: 0: No such file or directory,是否已弃用此语法?
  • @BigMoney 你想先运行 crontab -e 这样你就可以得到一个很好的 crontab 文件编辑窗口。
【解决方案2】:

你可以使用 crontab,我认为它已经安装在 OSX 上?

打开终端并运行crontab -e。这应该会打开一个编辑器。在那里你可以输入

@hourly /usr/bin/python database.py

【讨论】:

    【解决方案3】:

    根据 Rafael Santos 的建议,您可以像这样使用 cron:

    您输入:crontab -e 并添加这一行:

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

    它将每小时运行一次您的脚本。或者,如果您使用的是 Django,您可以使用 Celery 来做同样的事情。 (它有一个 crontab 类型)

    【讨论】:

      【解决方案4】:

      运行时间,加1h,然后每5s校验一次电流,旧时间+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)
      

      你应该把它添加为函数,因为我的代码很丑 xDD

      【讨论】:

        猜你喜欢
        • 2011-07-20
        • 2014-03-25
        • 2020-03-05
        • 1970-01-01
        • 2017-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多