【问题标题】:Running a python script in every 30 minutes using Crontab?使用 Crontab 每 30 分钟运行一次 python 脚本?
【发布时间】:2018-11-10 05:20:54
【问题描述】:

我想每 30 分钟运行一次 python 脚本。为此,我正在使用 crontab。 我是 crontab 的新手,我阅读并运行脚本 30 分钟我必须使用类似这样的查询:

*/30 * * * * python filename.py

但是我必须在哪里触发这个命令。

我试过了,

crontab -e

并将文件更改为,

*/30 * * * * python filename.py

有人可以解释我如何正确使用 crontab 吗?

PS:我想在我在 AWS ec2 实例上创建的服务器上每 30 分钟运行一次脚本,是否有替代解决方案?

我使用的是 Ubuntu 16.04

【问题讨论】:

  • 那么你的代码有什么问题?
  • 最好指定file.pypython 的完整路径。您可以使用which python 命令获取python的完整路径。

标签: python cron scheduled-tasks


【解决方案1】:

假设我有一个包含内容的 python 文件test.py

print "hello"

要安排它每 30 分钟运行一次,请使用

crontab -e

然后编辑添加

*/30 * * * * python /path-to-file/test.py

检查 cron 是否成功运行

grep CRON /var/log/syslog

在这里,您将在日志中看到类似

的行
May 31 14:25:01 shivam-PC CRON[17805]: (shivam) CMD (python /home/shivam/test.py)

注意:print 语句可能不会显示在日志中,因此请使用

*/30 * * * * python /path-to-file/test.py >> /path-to-file/out.txt

然后检查out.txt 的打印日志。

另一种解决方案是使用Celery

【讨论】:

  • */1 * * * * python /Cron_Job/cronex.py >> /Cron_Job/out.txt 在我使用这个的一分钟内,我看不到 crontab 的任何变化。跨度>
  • 您可能还想使用 */30 * * * * python /path-to-file/test.py >> /path-to-file/output 将标准错误捕获到输出文件。 txt 2&>1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
相关资源
最近更新 更多