linux crontab notify,Notify-send无法从crontab运行

问题描述

我制作了一个脚本,当我正在阅读漫画的新章节时,它应该通知我。我使用命令notify-send来做到这一点。当我试图在终端中运行它时,该程序工作。通知正在显示。但是,当我将它放在我的crontab中时,通知不会显示。我很确定该程序正在运行,因为我为它创建了一个文件。该文件已创建,但通知未显示。

这是我的剧本

#!/bin/bash

#One Piece Manga reminder

#I created a file named .newop that contains the latest chapter.

let new=$(cat ~/.newop)

wget --read-timeout=30 -t20 -O .opreminder.txt http://www.mangareader.net/103/one-piece.html

if (( $(cat .opreminder.txt | grep "One Piece $new" | wc -l) >=1 ))

then

(( new+=1 ))

echo $new

echo $new > ~/.newop

notify-send "A new chapter of One Piece was released."

else

notify-send "No new chapter for One Piece."

notify-send "The latest chapter is still $new."

fi

exit

这就是我在crontab中写的内容

0,15,30,45 12-23 * * 3 /home/jchester/bin/opreminder.sh

最佳解决方法

命令需要引用它们的位置。所以notify-send需要是/usr/bin/notify-send

所有命令都需要有完整的路径。

使用whereis notify-send命令查看命令”live”的位置

次佳解决方法

事情在13.04似乎有所不同,至少在Gnome Shell中是这样。

首先,这是env从用户zzyxy(非root用户)的cron作业运行时打印的内容:

HOME=/home/zzyxy

LOGNAME=zzyxy

PATH=/usr/bin:/bin

XDG_RUNTIME_DIR=/run/user/zzyxy

LANG=en_US.UTF-8

SHELL=/bin/sh

PWD=/home/zzyxy

要使notify-send正常工作,似乎有必要根据ubuntuforums.org上的DahitiF’s comment设置DBUS_SESSION_BUS_ADDRESS环境变量。只需将以下内容添加到您的实际工作描述中:

eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";

似乎没有必要设置DISPLAY。

第三种解决方法

命令notify-send在cron启动时不会在屏幕上显示消息。只需在脚本顶部添加目标显示,例如:

export DISPLAY=:0

第四种方法

至少对于Ubuntu 14.04,klrmr’s response above是正确的答案。似乎没有必要为notify-send设置DISPLAY或清晰表达完整路径,或者通常在$ PATH中设置其他任何路径。

下面是我用来在笔记本电脑的电池状态变得太低时关闭虚拟机的cron脚本。 klrmr上面的响应中的行设置DBUS_SESSION_BUS_ADDRESS是最终使警告正常工作的修改。

#!/bin/bash

# if virtual machine is running, monitor power consumption

if pgrep -x vmware-vmx; then

bat_path="/sys/class/power_supply/BAT0/"

if [ -e "$bat_path" ]; then

bat_status=$(cat $bat_path/status)

if [ "$bat_status" == "Discharging" ]; then

bat_current=$(cat $bat_path/capacity)

# halt vm if critical; notify if low

if [ "$bat_current" -lt 10 ]; then

/path/to/vm/shutdown/script

echo "$( date +%Y.%m.%d_%T )" >> "/home/user/Desktop/VM Halt Low Battery"

elif [ "$bat_current" -lt 15 ]; then

eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";

notify-send -i "/usr/share/icons/ubuntu-mono-light/status/24/battery-caution.svg" "Virtual machine will halt when battery falls below 10% charge."

fi

fi

fi

fi

exit 0

第五种方法

在我使用ubuntu 16.04的情况下,需要任何显式路径,我只是添加解决问题

DISPLAY=:0

在调用notify-send之前,在crontab的第一行。

参考资料

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值