为什么cronjobs不能用python-crontab执行?

时间:2017-09-14 08:12:34

标签: python cron ubuntu-16.04

我认为以下内容每分钟都会执行notify-send "Crontab Test"。但相反,似乎根本没有执行:

我的代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from crontab import CronTab
cron = CronTab(user=True)

# List all cron jobs
for job in cron:
    print(job)


# Create new job
job = cron.new(command='/usr/bin/notify-send "Crontab Test"', comment='Crontab Test')
job.minute.every(1)

print("job.is_enabled()={}".format(job.is_enabled()))
print("job.is_valid()={}".format(job.is_valid()))

# Commit changes
cron.write()

我的系统

  • Ubuntu 16.04(MATE),如果我在bash中执行notify-send "Crontab Test"它可以正常工作
  • python-crontab==2.2.4已安装

crontab文件

$ cat /var/spool/cron/crontabs/math 
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/tmpdl3P0o installed on Thu Sep 14 10:26:28 2017)
# (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)

* * * * * /usr/bin/notify-send "Crontab Test2" # Crontab Test2

* * * * * /usr/bin/notify-send "Crontab Test" # Crontab Test

* * * * * /usr/bin/notify-send "Crontab Test" # Crontab Test

即使将notify-send命令更改为没有参数的自编写Python脚本(带有可执行标志)的绝对路径也不起作用。

Cron正在运行

$ service cron status 
● cron.service - Regular background program processing daemon
   Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
   Active: active (running) since Do 2017-09-14 09:08:08 CEST; 1h 22min ago
     Docs: man:cron(8)
 Main PID: 696 (cron)
    Tasks: 1
   Memory: 7.4M
      CPU: 949ms
   CGroup: /system.slice/cron.service
           └─696 /usr/sbin/cron -f

日志:

$ grep cron /var/log/syslog
Sep 14 10:17:01 math-HP-EliteBook-Folio-1040-G3 CRON[25797]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Sep 14 10:20:25 math-HP-EliteBook-Folio-1040-G3 crontab[26516]: (math) LIST (math)
Sep 14 10:20:25 math-HP-EliteBook-Folio-1040-G3 crontab[26517]: (math) REPLACE (math)
Sep 14 10:21:01 math-HP-EliteBook-Folio-1040-G3 cron[696]: (math) RELOAD (crontabs/math)
Sep 14 10:26:28 math-HP-EliteBook-Folio-1040-G3 crontab[27919]: (math) LIST (math)
Sep 14 10:26:28 math-HP-EliteBook-Folio-1040-G3 crontab[27920]: (math) REPLACE (math)
Sep 14 10:27:01 math-HP-EliteBook-Folio-1040-G3 cron[696]: (math) RELOAD (crontabs/math)

crontab列出命令:

$ crontab -l

* * * * * /usr/bin/notify-send "Crontab Test2" # Crontab Test2

* * * * * /usr/bin/notify-send "Crontab Test" # Crontab Test

* * * * * /usr/bin/notify-send "Crontab Test" # Crontab Test

1 个答案:

答案 0 :(得分:0)

问题

GUI程序不起作用,因为默认情况下crontab在后​​台运行

解决方案

我需要设置环境变量DISPLAY=:0,因此命令是

DISPLAY=:0 /usr/bin/notify-send "Crontab Test"