How can I make a bash command run periodically?

前端 未结 8 1990
执笔经年
执笔经年 2020-12-07 20:26

I want to execute a script and have it run a command every x minutes.

Also any general advice on any resources for learning bash scripting could be really cool. I us

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 20:45

    Avoiding Time Drift

    Here's what I do to remove the time it takes for the command to run and still stay on schedule:

    #One-liner to execute a command every 600 seconds avoiding time drift
    #Runs the command at each multiple of :10 minutes
    
    while sleep $(echo 600-`date "+%s"`%600 | bc); do ls; done
    

    This will drift off by no more than one second. Then it will snap back in sync with the clock. If you need something with less than 1 second drift and your sleep command supports floating point numbers, try adding including nanoseconds in the calculation like this

    while sleep $(echo 6-`date "+%s.%N"`%6 | bc); do date '+%FT%T.%N'; done
    

提交回复
热议问题