Python Cron 作业未执行

Python Cron job not executed

我在 Ubuntu 14.05 上设置了一个 cron 作业,以执行 Python 脚本。这个 Python 脚本应该获取一些数据,将其存储在数据库中并通过 Boxcar 向我的 iPhone 发送通知。问题是,我没有收到任何通知。另外,我检查了我的数据库。没有添加新数据,所以我很确定脚本没有被执行。

我使用了以下命令:sudo crontab -e 并输入了以下内容:

30 09 * * * /usr/bin/python /home/jnevens/code/main.py

这应该每天在9:30执行main.py,对吧?

我的 Python 代码如下:

from tweet_mining import tweetFetcher
from rail import collectSchedules
from datetime import date, timedelta
from urllib import urlencode
from urllib2 import Request, urlopen

def go():
    twitter = tweetFetcher()
    tweetCount = twitter.main()

    delta = timedelta(days=1)
    d = date.today() - delta
    collectSchedules(d, d)
    push_not('Done!', 'Collected ' + str(tweetCount) + ' tweets')
    return

def push_not(title, message):
    url = 'https://new.boxcar.io/api/notifications'
    values = {'user_credentials' : '####',
              'notification[title]' : title,
              'notification[sound]': 'echo',
              'notification[long_message]': message}
    data = urlencode(values)
    req = Request(url, data)
    response = urlopen(req)
    return response.read()

go()

我是否需要重启才能使 cron 作业开始工作?我做错了什么?

如果服务器启用了邮件路由,请确保在 crontab 中设置了电子邮件地址,这样您就可以收到带有输出的邮件。

MAILTO=cron_output@example.com

还要确保将错误重定向到标准输出。

30 09 * * * /usr/bin/python /home/jnevens/code/main.py 2>&1

或者将您的输出重定向到本地日志文件并检查其中的内容。

如果可以,请在测试期间每分钟 运行 脚本,以便您可以实时查看问题所在。通常问题是环境 and/or 您的 shell 环境与 cron 运行 所在的环境之间的路径存在一些差异。

我总是在第一行脚本中添加解释器路径

#!/usr/bin/python" 

cron 文件中没有。也许这是一个问题。

您使用 Ubuntu,但在 Centos 中,您示例中的这一部分:“/usr/bin/python”告诉 cron 守护程序:用户对 运行 脚本具有什么权限。