??在 Linux 中可以使用 notify-send 命令发送桌面消息,再加上 crontab 就可以实现定时发送。但为了能够发送定制化的复杂消息,可以自己写脚本实现定时。下面的代码中使用 flock 防止脚本被多次执行。值得注意的是,在脚本中执行 notify-send 命令时,需要设置 DISPLAY 环境变量,即:DISPLAY=:0.0。代码如下所示:
#!/bin/bash
sleep_time=5
tip_inter=2400
lock_file=/tmp/.havearest.lock
function get_cur_ts()
{
current=`date "+%Y-%m-%d %H:%M:%S"`
timestamp=`date -d "$current" +%s`
echo $timestamp
}
function update_timestamp()
{
ts=`get_cur_ts`
echo $ts > $lock_file
}
function send_notify()
{
cur_time=`date "+%H:%M"`
DISPLAY=:0.0 notify-send -u critical $cur_time", have a rest!"
}
function periodic_notify()
{
echo "begin to periodicly notify ..."
while [ 1 -eq 1 ]
do
last_ts=`cat $lock_file`
if [ -z "$last_ts" ]; then
update_timestamp
sleep $sleep_time
continue
fi
cur_ts=`get_cur_ts`
diff=$[$cur_ts-$last_ts]
if [ $diff -gt $tip_inter ]; then
send_notify
update_timestamp
fi
sleep $sleep_time
done
}
function main()
{
if [ $# -ne 1 ]; then
echo "Usage: $0 tip_inter"
exit
fi
if [[ "$1" =~ ^[0-9]+$ ]]; then
tip_inter=$1
[ ! $tip_inter -gt $sleep_time ] && {
echo "tip_inter should be greater than $sleep_time!"
exit
}
else
echo "Error: $1 is not a number!"
exit
fi
if [ ! -f $lock_file ]; then
touch $lock_file
fi
(
flock -x -n -E 30 9
if [ $? -eq 30 ]; then
echo "Cannot create lock on '$lock_file'. Is another process running?"
exit
fi
periodic_notify
) 9< $lock_file
}
main $*
??执行效果如下:
$ ./periodic_notify.sh 10
begin to periodicly notify ...
??桌面提醒如下:
|