我创建了一个自定义目录,在其中放置了一些我最喜欢的壁纸。我制作了一个脚本来检查这个目录,计算 PNG 的数量,然后随机设置一张图片作为壁纸。它看起来像这样:
#!/bin/bash
#number of images in wallpaper folder
cd $HOME/Favourite\ wallpapers/
numImages=`ls *.png | wc -l`
#randomly chose one number
randomNum=$[ ( $RANDOM % $numImages ) + 1 ]
#command to set wallpaper
gsettings set org.gnome.desktop.background picture-uri file://$HOME/Favourite\ wallpapers/00$randomNum.png
Run Code Online (Sandbox Code Playgroud)
现在,我怎样才能让这个脚本在每次登录时运行(这很容易),或者如果没有在登录时运行,则每天运行一次?
问题是我经常挂起我的 Ubuntu,然后在明天早上唤醒它,所以在这种情况下我再也不会登录了。将此脚本设置为启动作业对我没有帮助,因为显然,当从挂起状态唤醒时,我从不重新登录。我也不能简单地通过cron作业设置它,因为在我登录的情况下,墙纸将更改两次一天几次。
附注。任何人都可以随意使用此脚本cron(只需设置您自己的路径和文件名模板或等待像我这样的解决方案:)
将此设置为启动应用程序:
#!/bin/bash
# Based on /etc/cron.daily/apt
check_stamp()
{
stamp="$1"
interval="$2"
if [ $interval -eq 0 ]; then
echo "check_stamp: interval=0"
# treat as no time has passed
return 1
fi
if [ ! -f $stamp ]; then
echo "check_stamp: missing time stamp file: $stamp."
# treat as enough time has passed
return 0
fi
# compare midnight today to midnight the day the stamp was updated
stamp_file="$stamp"
stamp=$(date --date=$(date -r $stamp_file --iso-8601) +%s 2>/dev/null)
if [ "$?" != "0" ]; then
# Due to some timezones returning 'invalid date' for midnight on
# certain dates (eg America/Sao_Paulo), if date returns with error
# remove the stamp file and return 0. See coreutils bug:
# http://lists.gnu.org/archive/html/bug-coreutils/2007-09/msg00176.html
rm -f "$stamp_file"
return 0
fi
now=$(date --date=$(date --iso-8601) +%s 2>/dev/null)
if [ "$?" != "0" ]; then
# As above, due to some timezones returning 'invalid date' for midnight
# on certain dates (eg America/Sao_Paulo), if date returns with error
# return 0.
return 0
fi
delta=$(($now-$stamp))
# intervall is in days, convert to sec.
interval=$(($interval*60*60*24))
echo "check_stamp: interval=$interval, now=$now, stamp=$stamp, delta=$delta (sec)"
# remove timestamps a day (or more) in the future and force re-check
if [ $stamp -gt $(($now+86400)) ]; then
echo "WARNING: file $stamp_file has a timestamp in the future: $stamp"
rm -f "$stamp_file"
return 0
fi
if [ $delta -ge $interval ]; then
return 0
fi
return 1
}
update_stamp()
{
stamp="$1"
touch $stamp
}
STAMP=$1
INTERVAL=$2
export DISPLAY=:0.0
while true; do
if check_stamp $STAMP $INTERVAL; then
# Do whatever you want
/path/to/your/script
# Update stamp
update_stamp $STAMP
fi
# Sleep 10 min
sleep 600
done
Run Code Online (Sandbox Code Playgroud)
将/path/to/your/script(在 while 循环内)替换为脚本的路径。
调用此脚本首先传递文件的路径,该文件将用作标记,后跟以天为单位的间隔,例如scriptname /home/user/stampfile 1. 它将无休止地运行,并每 10 分钟 ( sleep 600)对照戳记检查当前时间。如果差异大于间隔,它会运行您的脚本并更新戳记。
| 归档时间: |
|
| 查看次数: |
3110 次 |
| 最近记录: |