Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

python - Run a process every alternate x hours

I have a python script which I am running like this as shown below:

python3 ./bin/abc.py --log_file ./web/prr.log

Now I need to make sure that above process runs after every 3 hours. Below is the flow:

  • If the process is running already, then kill the process and sleep for 3 hours.
  • After sleeping for 3 hours, if process is not running, start the process again by executing above python command and then sleep for three hours.
  • Repeat the above process.

So meaning, I need to make sure that my process is running every alternate 3 hours so I need to find a way to kill the process after every 3 hours. I was thinking to use watch command here but not sure how can I use it here. I am working with Ubuntu 14.

Note: I can't modify the python script so I need to do it from outside of it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This seems like an ideal use case for crontab. I'd write 2 bash scripts that run every 3 hours via cron. So something like the following:

#ScriptA.sh
ifProcessRunning
    KillProcess

#ScriptB.sh
ifProcessNotRunning
    StartProcess

#CronTab
0,6,12,18 * * * * ScriptA.sh
3,9,15,21 * * * * ScriptB.sh

For killing the process you can use any normal unix command, so piping a ps aux and running kill within the shell script could work.

Hopefully this helps -- comment if you want me to flesh things out more!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...