Python定时任务未执行

2024-10-05 14:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在ubuntu14.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作业才能开始工作吗?我做错什么了?你知道吗


Tags: 数据frompyimport命令脚本数据库message
2条回答

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

#!/usr/bin/python" 

cron文件中没有。也许这是个问题。你知道吗

您使用的是Ubuntu,但在Centos中,示例中的这一部分是:“/usr/bin/python”告诉cron deamon:用户有什么权限运行脚本。你知道吗

确保您在crontab中设置了电子邮件地址如果服务器启用了邮件路由,那么您可以接收带有输出的邮件。你知道吗

MAILTO=cron_output@example.com

还要确保将错误重定向到stdout。你知道吗

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

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

如果可以的话,在测试过程中每分钟运行一次脚本,这样您就可以实时看到哪里出了问题。通常问题是您的shell环境和cron运行的环境之间的环境和/或路径存在一些差异。你知道吗

相关问题 更多 >