【问题标题】:Schedule a Python script in crontab on Google Compute Engine VM在 Google Compute Engine VM 上的 crontab 中安排 Python 脚本
【发布时间】:2019-01-26 03:20:58
【问题描述】:

我已经安排我的 Python 脚本每小时执行一次,方法是在 shell 中键入 crontab -e,然后将这行文本添加到 cron 文件中:

0 * * * * /usr/bin/python /home/myUserName/automatedProject/test.py &>> /home/myUserName/automatedProject/log.txt

但无论我尝试什么变体,它都不会执行。

作为测试脚本,我使用 Jessica Yung 的 simple script 将时间戳附加到文件中:

#! /usr/bin/env python
import time
filename = "record_time.txt"
current_time = time.strftime('%a %H:%M:%S')
with open(filename, 'a') as handle:
    handle.write(str(current_time))
    handle.write('\n')

【问题讨论】:

  • Cron 不以your username 运行。因此,不要尝试根据您的主目录访问文件文件。 cron 日志文件因 Linux 发行版而异:在 /var/log/syslog 中查找 cron 错误。这也可能对您有所帮助:askubuntu.com/questions/418237/how-to-detect-error-in-cron-jobs
  • 嗨@JohnHanley,我已将所有内容移至/opt/*,但Google Compute Engine VM 仍不执行我的cron 作业,即使我将cron 时间/日期选项设置为@987654329 @(所有 5 个选项为“任何”)
  • 日志文件向您展示了什么?
  • cron 确实在您的用户 ID 下运行 crontab 命令。请注意,Python 脚本直接写入当前目录中名为 record_time.txt 的文件,该目录应该是您的主目录。检查该文件以查看命令是否正在执行。该脚本不打印任何内容,因此重定向到log.txt 不会收集任何内容。 (在将命令放入 crontab 之前手动运行命令总是一个好主意,以确保它在正常情况下的行为符合您的预期。)
  • 我的cron 不喜欢&>> 重定向,因为这是bash 语法,而cron 使用普通的旧sh 来运行crontab 作业。尝试将其从 &>> /path/to/logfile 更改为 >> /path/to/logfile 2>&1,这是传统的 sh 做同样事情的方式。如果这不能解决问题,那么让我们从一开始并检查cron 服务是否实际运行(执行ps -efa | grep cron)。

标签: python google-cloud-platform virtual-machine google-compute-engine


【解决方案1】:

在带有 Ubuntu 16.04 VM 的 Google Compute Engine 中,用户级 cron 作业似乎根本没有启动;但是,根级作业按预期工作。

而不是像这样编辑 crontab:

crontab -e

使用sudo crontab -e

一个简单的工作示例是* * * * * /usr/bin/python /home/myUserName/test.py 每分钟运行一次test.py

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多