我有一个脚本,我需要以certian间隔运行一个特殊的函数,而其余的脚本正常执行。
例如......我希望每小时获取磁盘数据,而其余脚本每秒收集一次过程数据......
这里我有一个基本的脚本来测试它,但是它没有按预期工作......
#!/bin/bash
function test () {
echo "This line should print all the time..."
}
function test2 () {
echo "This line should only print every 3 seconds..."
sleep 3
}
while :
do
test &
test2
done
任何帮助都是......有帮助的:-D
谢谢!
答案 0 :(得分:1)
创建一个具有无限循环和睡眠的函数, 并在后台启动它。 它会定期做东西, 而其余的脚本可以继续。
periodic() {
while :; do
echo periodic
date
sleep 3
done
}
main() {
echo in the main...
sleep 5
echo still in the main...
sleep 1
echo in the main in the main in the main
}
periodic &
periodic_pid=$!
echo periodic_pid=$periodic_pid
main
echo time to stop
kill $periodic_pid
答案 1 :(得分:1)
在后台循环中运行periodic函数并使用sleep在迭代之间等待3秒。 如果您需要在主进程的上下文中完成某些操作,请从后台循环向其发送信号。 不要忘记在退出时终止你的后台进程。
#!/bin/sh
terms=0
trap ' [ $terms = 1 ] || { terms=1; kill -TERM -$$; }; exit' EXIT INT HUP TERM QUIT
#In case the periodic stuff needs to run in the ctx of the main process
trap 'echo "In main ctx"' ALRM
test() {
echo "This line should print all the time..."
}
test2__loop()
{
while :; do
echo "This line should only print every 3 seconds..."
kill -ALRM $$
sleep 3
done
}
test2__loop &
while :
do
test
sleep 1
done