Crontab 不工作 - EC2 - Amazon Web Service (aws) - Ubuntu

Crontab doesn't work - EC2 - Amazon Web Service (aws) - Ubuntu

我不知道为什么,但我的 crontab 在 Ubunut 14 中不工作。0.x - Amazon Web Services (AWS) EC2。

我已经尝试了很多东西。

例如

sudo nano test.cron

--> * * * * * sudo /usr/bin/python3 /home/ubuntu/Dropbox/MeteoData/test.py

我也试过了

--> * * * * * /usr/bin/python3 /home/ubuntu/Dropbox/MeteoData/test.py

然后是

chrontab test.cron

crontab -l 

会给我下一个结果:

MAILTO=myemail@hotmail.com
* * * * * sudo /usr/bin/python3 /home/ubuntu/Dropbox/MeteoData/test.py

MAILTO=myemail@hotmail.com
* * * * * /usr/bin/python3 /home/ubuntu/Dropbox/MeteoData/test.py

但是 crontab 什么都不做:(

即使如此,如果我正常执行脚本,python 脚本也能完美运行...

import sys, urllib
from selenium.webdriver.common.proxy import *
from bs4 import BeautifulSoup
import csv
import re, os
import urllib.parse
from time import localtime, gmtime, strftime, mktime, sleep

from geopy.geocoders import Nominatim
import csv
from geopy.geocoders.googlev3 import GoogleV3
from _ast import Try
import datetime

def main(args):

    keys = ['Name', 'Latitude','Longitude','Altitude','firstDay']     
    f = open("testNUUUUU.csv", 'w')
    try:
        writer = csv.writer(f,delimiter=',', lineterminator='\n')
        writer.writerow( keys )
    finally:
        f.close()


if __name__ == "__main__":

    try:
        main(sys.argv[1:]) # chop off the sys.argv[0] (script name) and pass the rest.
    except KeyboardInterrupt:
        print('\nUser Break.')

此外,我很确定 crontab 服务器是 运行 :

sudo service cron restart
cron stop/waiting
cron start/running, process 3210

没有任何结果:'(


因此,如果我在终端中执行代码 --> 它有效(它将创建文件)

如果我想让crontab执行代码,那是行不通的:'(

换句话说,有人可以帮忙吗?

将您的脚本放入文件 test.py

开头
#!/usr/bin/python3

然后使用

授予该脚本执行权限
chmod a+x test.py

并在 crontab.

中使用 test.py 文件的完整路径

请参阅 execve(2) which is handling the shebang

的文档

我的首要任务:如果您忘记在 crontab 文件末尾添加换行符。换句话说,crontab 文件应该以空行结尾。

下面是这个问题的手册页中的相关部分(man crontab 然后跳到最后):

cron requires that each entry in a crontab end in a newline character. If the last entry in a crontab is missing the newline, cron will consider the crontab (at least partially) broken and refuse to install it.


解决方案 : 显然,整个设置从一开始就是正确的。我唯一没有注意到的是,crontab 将在 home/____/ 目录中执行。由于我原来的 python 脚本需要一些其他文件(由于 错误的 目录他找不到的文件。),因此无法正确执行它+ 使用测试脚本,我没有注意到结果写在 home/___/ 目录中....

因此...

解决方案

清理/删除所有 crontab(我猜是可选的)

crontab -r

创建一个 crontab 任务文件

sudo nano myCrontabTask.cron

编辑 crontab 任务文件

#
# 1 * * * * <-- crontab task, which will be executed every hour
# cd /home/ubuntu/Dropbox/MeteoData/ <-- directory where everything should happen
# sudo /usr/bin/python3 /home/ubuntu/Dropbox/MeteoData/scriptGetMeteoData.py <-- execute the python script
#
1 * * * * cd /home/ubuntu/Dropbox/MeteoData/ && sudo /usr/bin/python3 /home/ubuntu/Dropbox/MeteoData/scriptGetMeteoData.py

将 crontab 任务添加到 crontab

crontab myCrontabTask.cron

检查是否添加了crontabTask

crontab -l

如果一切正确,您将看到您的 crontab 任务

  • 通过此解决方案,它将在 用户级别执行 - 如果你想在 root 上执行 en crontab-task-等级 你应该使用

    crontab -e

没有创建 .cron 文件