2017-07-21 35 views
2

我有一个脚本,我需要以certian间隔运行一个spicific函数,而脚本的其余部分正常执行。每5秒执行一次bash函数,但让脚本的其余部分运行

比如......我想磁盘数据每隔一小时,而脚本的其余部分采集过程数据每一秒......

在这里,我有一个基本的脚本来测试这一点,但它不是按预期工作...

#!/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

谢谢!

回答

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 
+0

这很好!我对它进行了一些更改以捕获int并退出其他进程,但这让我走上了正轨!太感谢了! – Joe

1

在后台循环中运行周期性函数,并使用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 
+0

这也不错......我结束了使用ctrl-c的陷阱来杀死退出时的背景pid ......感谢您的贡献! – Joe

相关问题