无法使用crontab更改桌面背景

我已经在crontab中安排了一个作业,使用以下脚本在Lubuntu中每分钟随机更改桌面背景:

#!/bin/bash export DISPLAY=:0 PHOTOS_PATH=~/Pictures/wallpapers/ number_of_photos=$(ls $PHOTOS_PATH | wc -l) # generates a random number in range 1 through $number_of_photos random=$( shuf -i 1-$number_of_photos -n 1 ) # returns the name of the file at line number $random of `ls` output photo_file=$(ls $PHOTOS_PATH | head --lines=$random | tail --lines=1) pcmanfm --set-wallpaper=$PHOTOS_PATH/$photo_file exit 0 

但每分钟,屏幕上都会显示以下错误消息:

在此处输入图像描述

问题在于发出命令pcmanfm的脚本行,因为(根据我的实验)此消息恰好出现在该命令的执行中。 我也从tty1里面运行这个脚本,它成功地改变了我的桌面背景,没有错误。 我怎样才能用crontab克服这个问题?

这是我的脚本版本。 通过这种方法,我们不需要担心我们应该导出哪个环境变量,因为我们为当前用户的会话导出所有可用变量。

 #!/bin/bash # NAME: lubuntu-wp-changer # Initial variables ITEMS_PATH="$HOME/Pictures/wallpapers" ITEMS=("$ITEMS_PATH"/*) # Check whether the user is logged-in, if yes export the current desktop session environment variables [ -z "$(pgrep lxsession -n -U $UID)" ] && exit 0 || export $(xargs -0 -a "/proc/$(pgrep lxsession -n -U $UID)/environ") >/dev/null # Generates a random number in the range determinated by the number of the items in the array ${ITEMS[@]} ITEM=$(( ($RANDOM) % ${#ITEMS[@]} )) # Set the wallpaper pcmanfm --set-wallpaper="${ITEMS[$ITEM]}" exit 0 

这是我的Cronjob,每三秒更换一次壁纸:

 * * * * * bash -c 'for i in {1..20}; do $HOME/lubuntu-wp-changer; sleep 3; done' 

结果如下:

在此处输入图像描述

更多细节可以在我的GitHub项目中找到: cron-gui-launcher 。