在Linux中使用notify-send发送定期提醒

  在 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 ...

  桌面提醒如下:
桌面提醒
如果执行上述命令后没有显示桌面提醒,则需要确认 notification daemon相关的软件包是否安装,例如,在 debian 里面使用mate桌面,则需要安装 mate-notification-daemon/Debian

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值