无法使用 crontab 更改桌面背景

无法使用 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 克服这个问题?

答案1

以下是我改编的剧本。方法我们不需要担心应该导出哪个环境变量,因为我们导出当前用户会话的所有可用变量。

#!/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-启动器

相关内容