如何限制Bash脚本中函数的重复执行频率
限制Bash脚本函数调用频率避免程序崩溃
我给Bash脚本设置了键盘快捷键调用,但连续快速按下快捷键时,脚本内启动的程序会崩溃。简化后的脚本如下:
#!/bin/bash # Config monitor="eDP-1" wallpaper_dir="$HOME/Pictures/bg" # Get list of wallpaper file paths file_listing=($wallpaper_dir/*) function hyprpaper_set() { # Get one random file path file_random=("${file_listing[RANDOM % ${#file_listing[@]}]}") # Set wallpaper with hyprctl hyprctl hyprpaper wallpaper "$monitor,$file_random" } hyprpaper_set
我希望限制hyprpaper_set函数的调用频率,例如每秒仅允许调用一次,以避免异常问题。尝试过使用date +"%S"比较时间、SECONDS变量计算耗时、export全局变量传递值,但都未能解决问题,恳请提供帮助!
锁机制解决方案
锁机制方案效果良好,修改后的脚本如下:
function hyprpaper_set() { # Set lock lockdir=/tmp/myscript.lock if mkdir -- "$lockdir"; then # Get one random file path file_random=("${file_listing[RANDOM % ${#file_listing[@]}]}") # Set wallpaper with hyprctl hyprctl hyprpaper wallpaper "$monitor,$file_random" # Remove lockdir when the script finishes, or when it receives a signal trap 'rm -rf -- "$lockdir"' 0 # remove directory when script finishes else printf >&2 'cannot acquire lock, giving up on %s\n' "$lockdir" exit 0 fi } hyprpaper_set
内容的提问来源于stack exchange,提问作者koahv
相关产品推荐
相关产品推荐

