How can I tell Perl to run some code every 20 seconds?

后端 未结 8 803
余生分开走
余生分开走 2021-02-13 15:45

How can I tell Perl to run some code every 20 seconds?

8条回答
  •  感情败类
    2021-02-13 16:19

    While the sleep function will work for some uses, if you're trying to do "every 20 seconds, forever", then you're better off using an external utility like cron.

    In addition to the possible issue of drift already mentioned, if your sleep script exits (expectedly or otherwise), then it's not going to run again at the next 20 second mark.

    @Blrfl is correct, and I feel sheepish. That said, it's easy enough to overcome.

    * * * * * /path/to/script.pl
    * * * * * sleep 20 && /path/to/script.pl
    * * * * * sleep 40 && /path/to/script.pl
    

    You could also take a hybrid approach of putting a limited count sleep loop in the script and using cron to run it every X minutes, covering the case of script death. Anything more frequent than 20 seconds, I would definitely take that approach.

提交回复
热议问题