Last active
August 7, 2023 09:04
-
-
Save bahamas10/4d43660926bde28552db to your computer and use it in GitHub Desktop.
setInterval in bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# simple bash script to simulate JavaScript's setInterval (blocking) | |
# | |
# Author: Dave Eddy <[email protected]> | |
# Date: September 27, 2014 | |
# License: MIT | |
setInterval() { | |
local func=$1 | |
local sleeptime=$2 | |
local _start _end _delta _sleep | |
while true; do | |
_start=$(date +%s) | |
#echo "$_start: starting work" | |
# do work (unknown amount of time) | |
"$func" | |
_end=$(date +%s) | |
_delta=$((_end - _start)) | |
_sleep=$((sleeptime - _delta)) | |
#echo "$_end: finished doing work, took $_delta seconds, sleeping for $_sleep seconds" | |
sleep "$_sleep" | |
done | |
} | |
dowork() { | |
# this is where your code would go | |
echo -n 'doing work... ' | |
sleep 2 | |
echo 'done' | |
} | |
# setInterval for 5 seconds. in this example, because `dowork` takes 2 seconds to run, | |
# it will be called every 3 seconds, for a total of 5 seconds elapsed time. | |
echo "starting loop, will sleep 5 seconds between iterations" | |
setInterval dowork 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment